Testing quandary
Fair warning: This is not explicitly topical to the group's chosen project or platform, but I think it raises a valid and interesting TDD question, so I'm posting it here for feedback.
I've been writing a fair bit of Python code today using TDD. I'm moving the data for a project from Access to XML, which means I won't be able to simply declare a field as Autonumber and forget about it. I need to generate ID numbers which are unique in a particular domain... and I can't for the life of me figure out how to write any meaningful tests!
Here's the spike I wrote (yes, I know it executes in polynomial time):
class IDGenerator:Any ideas for tests that would express the problem? (Or, for that matter, for an algorithm with linear scalability?)
def __init__(self):
self.ids = []
def newID(self):
while True:
i = int(random.random() * (10 ** 8))
if i not in self.ids:
self.ids.append(i)
return i

1 Comments:
I think that testing that code will always generate a unique value in a domain is not something that can be done with unit testing short of executing the test as many times as the number of possible combinations.
There is, however, something called static analysis in which you insert assertions at the beginning and and end of a procedure (preconditions and postconditions), and the static analyzer actually attempts to prove that the assertion for the postcondition is true given the code and any preconditions. There is a subset of ADA, a subset of Java, and there are a few Functional programming languages for which static analysis is possible/available.
In the case of your algorithm, I think even a static analyzer would run into a halting problem unless the random number generator also had statically provable attributes that could be used to guarantee that your code must eventually halt.
Post a Comment
<< Home