0

I have data structure queue with 2 operations:

typedef struct queue queue

void enqueue(queue *q, void *elem);

void *dequeue(queue *q);

queue *read_from_file(const char *path);

I want to write assert for the queue like:

bool assert_queue_equals(queue *q, ...){
    //dequeue and compare till the end of varargs
}

The problem is such an assert contains side effect and modifies the input queue which I think is a bad practice for writing assertions to be used in unit tests.

Is using impelemtation details to traverse the queue without modifying it better?

  • What is supposed to be compared between queues? Or, in other words, what makes 2 queues to be equals? – Laiv Apr 23 at 10:54
  • @Laiv 2 queues are considered equal if they contain equal pointers in the same order. – Some Name Apr 23 at 11:04
  • Is assert_queue_equals a test function, or part of of the queue operations? If the former, then it's absolutely free to create two queues and pull them apart to test equality. But your code looks like the latter: you are providing it as a mean of testing if two queues are the same in production. In that case, modifying the queues definitely is a bad idea and you should have it examine the elements directly. – David Arno Apr 23 at 12:27
1

The problem is such an assert contains side effect and modifies the input queue which I think is a bad practice for writing assertions to be used in unit tests.

Modifying the queue during the assert is fine, assuming that this test is the only bit of code with a reference to the queue.

One common practice in designing tests is to use a single assertion to verify the behavior at the end of the scenario, so an assertion that destroys the utility of the queue when it is measured isn't necessarily a problem.

It's not ideal, either: "asking the question shouldn't change the answer". But not all API are designed with that goal in mind, and you may need to make trade offs.

Is using implementation details to traverse the queue without modifying it better?

Not usually, no -- especially not if you are intending the test to be a design aid that allows you to vary the underlying implementation (aka test driven design).

What may help is to have it clear in your mind what the required behavior is, and then to write clear descriptions of the behavior and verify that's what is observed.

You may find that Kevlin Henney's Recently Used List demonstration helps to clarify the distinction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.