3

Background

I am trying to add unit tests for a tree data structure I am building (python 3). The tree structure uses sets (unordered) and I am struggling to find ways to test certain methods of my tree class.

Example

Given the diagramed tree...I have a method that will detach a node (say #2) and then choose one of it's children (3 or 4) to take it's place instead of parenting them both to node 1. (This is useful in the case that say #2 is the root and we still want 3 and 4 to be related when 2 is discarded.)

      1----------+                     2        1----------+
      |          |                              |          |
  +---2---+      |    Detaching Node "2"        3---+      |
  |       |      11        -->                 /|\  |      11
  3       4     /| \                          5 6 7 |     /| \
 /|\     /|\  12 13 14                              4   12 13 14
5 6 7   8 9 10                                     /|\
                                                  8 9 10

The Problem

Sets are unordered and the way I select the child (out of 3 and 4) is to check if node 2 has children, then pop off a child from his set of children and make that the one. Because sets are unordered, I get (seemingly) random results in my test cases when I pop the child off.

Question

What should my strategy be to test a method like this (I've read about testing difficulties when using the random module, but I've also read that sets do have some sort of a predictable order)? Should I just test around this problem? Should I try to figure out what order the set will be "popped" in?

2
  • 2
    First question: Is this random behavior acceptable, meaning the implementation is correct? Commented Aug 5, 2016 at 19:25
  • Yes, absolutely. For this method I don't care which child it picks, as long as they stay related. Commented Aug 5, 2016 at 19:26

1 Answer 1

1

Test whether the method does the thing it's supposed to do. After the operation, has the correct node been replaced by one of its children? If so, great! If not, report a failure.

You don't need to assert that it's been replaced by any specific child.

Sign up to request clarification or add additional context in comments.

1 Comment

Good point, I got too caught up with how cool assert equal is that I forgot about the other assertion methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.