diff --git a/u01/node.cpp b/u01/node.cpp index 9719011..16e22f8 100644 --- a/u01/node.cpp +++ b/u01/node.cpp @@ -1,7 +1,19 @@ #include +#include #include "node.h" +unsigned int node::node_id = 0; + +node::node(const std::string &name) : name(name) { + node_id++; + if (name.empty()) { + std::stringstream node_sm; + node_sm << "node_" << node_id; + this->name = node_sm.str(); + } +} + node::~node() { std::cout << "enter ~node() of \"" << get_name() << "\"" << std::endl; for (node *child : children) { diff --git a/u01/node.h b/u01/node.h index 58d767f..5659d42 100644 --- a/u01/node.h +++ b/u01/node.h @@ -4,7 +4,7 @@ class node { public: - node(const std::string &name); + node(const std::string &name = ""); virtual ~node(); std::string get_name() const; void set_name(const std::string new_name); @@ -15,4 +15,5 @@ public: private: std::string name; std::vector children; + static unsigned int node_id; }; diff --git a/u01/tests.cpp b/u01/tests.cpp index 5faeba6..f6e384d 100644 --- a/u01/tests.cpp +++ b/u01/tests.cpp @@ -33,3 +33,24 @@ TEST_CASE("Get children") { } delete n; } + +TEST_CASE("Global node counting") { + node *n = new node(); + + // TODO: ensure this test starts at node_id 0 (currently this is undefined + // based on order the tests are run) for the time being, this gets the offset + int node_id_start = std::stoi(n->get_name().substr(5)); + // this tests if the node id was correctly extracted + REQUIRE(n->get_name() == "node_" + std::to_string(node_id_start)); + + for (std::size_t i = 0; i < 5; i++) { + n->add_child(new node()); + } + n->add_child(new node("explicit name")); + for (std::size_t i = 0; i < 5; i++) { + REQUIRE(n->get_child(i)->get_name() == + "node_" + std::to_string(node_id_start + 1 + i)); + } + REQUIRE(n->get_child(5)->get_name() == "explicit name"); + delete n; +}