472,981 Members | 1,558 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,981 software developers and data experts.

Test-driven development of random algorithms

I'm working on some functions that, essentially, return randomly generated
strings. Here's a basic example:

def rstr():
"""Return a random string based on a pseudo
normally-distributed random number.
"""
x = 0.0
for i in range(12):
x += random.random()
return str(int(x)+6))

I want to do test-driven development. What should I do? Generally, any
test I do of the form

assert rst() == '1'

will fail more often than not (about 85% of the time, by my estimate). An
easy work around would be to do this:

assert rstr() in [str(n) for n in range(-6, 6)]

but (1) that doesn't scale very well (what if rstr() could return one of
a billion different strings?) and (2) there could be bugs which only show
up probabilistically, e.g. if I've got the algorithm wrong, rstr() might
return '6' once in a while.

Does anyone have generic advice for the testing and development of this
sort of function?
--
Steven D'Aprano

Nov 14 '06 #1
2 1718
Steven D'Aprano wrote:
I'm working on some functions that, essentially, return randomly generated
strings. Here's a basic example:

def rstr():
"""Return a random string based on a pseudo
normally-distributed random number.
"""
x = 0.0
for i in range(12):
x += random.random()
return str(int(x)+6))

I want to do test-driven development. What should I do? Generally, any
test I do of the form

assert rst() == '1'

will fail more often than not (about 85% of the time, by my estimate). An
easy work around would be to do this:

assert rstr() in [str(n) for n in range(-6, 6)]

but (1) that doesn't scale very well (what if rstr() could return one of
a billion different strings?) and (2) there could be bugs which only show
up probabilistically, e.g. if I've got the algorithm wrong, rstr() might
return '6' once in a while.

Does anyone have generic advice for the testing and development of this
sort of function?
"Design for Testability". In library code, never call the functions in the
random module. Always take as an argument a random.Random instance. When
testing, you can seed your own Random instance and all of your numbers will be
the same for every test run.

This kind of design is A Good Thing(TM) outside of unit tests, too. They aren't
the only places where one might want to have full control over the sequence of
random numbers.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Nov 14 '06 #2
Robert Kern <ro*********@gmail.comwrites:
Steven D'Aprano wrote:
Does anyone have generic advice for the testing and development of
this sort of function?

"Design for Testability". In library code, never call the functions
in the random module. Always take as an argument a random.Random
instance. When testing, you can seed your own Random instance and
all of your numbers will be the same for every test run.
Even better, you can pass a stub Random instance (that fakes it) or a
mock Random instance (that fakes it, and allows subsequent assertion
that the client code used it as expected). This way, you can ensure
that your fake Random actually gives a sequence of numbers designed to
quickly cover the extremes and corner cases, as well as some normal
cases.

This applies to any externality (databases, file systems, input
devices): in your unit tests, dont pass the real externality. Pass a
convincing fake that will behave entirely predictably, but will
nevertheless exercise the functionality needed for the unit tests.

This is one of the main differences between unit tests and other
kinds. With unit tests, you want each test to exercise as narrow a set
of the client behaviour as feasible. This means eliminating anything
else as a possible source of problems. With other tests -- stress
tests, acceptance tests, and so on -- you want to exercise the entire
application stack, or some significant chunk of it.

--
\ "It is the mark of an educated mind to be able to entertain a |
`\ thought without accepting it." -- Aristotle |
_o__) |
Ben Finney

Nov 14 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Berthold Hoellmann | last post by:
Hello, When I use ./configure --with-thread --with-fpectl --with-signal-module \ --with-pymalloc --enable-shared --with-cxx=g++ make test on 2.3.3 I get
0
by: Remy Blank | last post by:
Ok, here we go. I added the possibility for tests using the unittest.py framework to be skipped. Basically, I added two methods to TestCase: TestCase.skip(msg): skips unconditionally...
4
by: Edvard Majakari | last post by:
Hi, I just found py.test and converted a large unit test module to py.test format (which is actually almost-no-format-at-all, but I won't get there now). Having 348 test cases in the module and...
0
by: Andrea M. Segovia | last post by:
I just compiled (but did not install) perl 5.8.0 on an SGI Origin 300 server (IP35) running IRIX 6.5.20m. Make test reported one test error, which I narrowed down to .../lib/ExUtils/t/Constant.t...
0
by: Jussi Mononen | last post by:
Hi, I'm having problems to successfully execute the test scripts on a Compaq host ( OSF1 tr51bdev V5.1 2650 alpha ). Almost all tests end up with the following error message "PARI: *** ...
4
by: arotem | last post by:
Hi, I am trying to call an unbound method (PrintInput) with the object instance as the first argument but getting the following error: "TypeError: unbound method PrintInput() must be called with...
6
by: ypjofficial | last post by:
HI, I have following terrific confusion. class test { public: int i; int * j; int **k;
2
by: Netkiller | last post by:
#!/usr/bin/python # -*- coding: utf-8 -*- """ Project: Network News Transport Protocol Server Program Description: 基于数据库的新闻组,实现BBS前端使用NNTP协议来访问贴子...
7
by: laura | last post by:
Hi, I have a variable of type double. I need to know if there is an integer number store there. How can I test that ? I also have a default precision for doing this operation. Many thanks,...
27
by: brad | last post by:
Does anyone else feel that unittesting is too much work? Not in general, just the official unittest module for small to medium sized projects? It seems easier to write some quick methods that are...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.