Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your code can be refactored to reduce the amount of code and therefore the amount of code that you need to test. Let's look at what you want:</p> <ul> <li>Roll a dice (<code>roll_a_dice</code>)</li> <li>Roll a dice a number of times (<code>roll_dice</code>)</li> <li>Get a number of rolls in which a dice has been rolled a number of times (<code>roll_some_dice</code>)</li> </ul> <p>Let's rewrite <code>roll_dice</code> first. We basically want to call <code>roll_a_dice</code> a number of times and put the results in a list:</p> <pre><code>def roll_dice(sides=6, count=1): """Return a list of integers (most function except this)""" return [roll_a_dice(sides) for i in xrange(count)] </code></pre> <p>Let's do the same thing with <code>roll_some_dice</code>: we want to call <code>roll_dice</code> a number of times and put the results in a list:</p> <pre><code>def roll_some_dice(sides=6, count=1, times=1): """Return a list of list containing integers""" return [roll_dice(sides, count) for i in xrange(times)] </code></pre> <p>Lastly, <code>rolling_dice</code> still contains some logic:</p> <pre><code>def rolling_dice(sides=6, count=1): """Yielding integers `count` times""" while count: count -= 1 yield roll_a_dice(sides) </code></pre> <p>The code is now a lot easier to check for errors and easier to unit test:</p> <pre><code>import random def roll_a_dice(sides=6): """Return an integer x where `x &gt;= 1 &lt;= sides`""" return random.randint(1, sides) def roll_dice(sides=6, count=1): """Return a list of integers (most function except this)""" return [roll_a_dice(sides) for i in xrange(count)] def roll_some_dice(sides=6, count=1, times=1): """Return a list of list containing integers""" return [roll_dice(sides, count) for i in xrange(times)] def rolling_dice(sides=6, count=1): """Yielding integers `count` times""" while count: count -= 1 yield roll_a_dice(sides) </code></pre> <p>You can now write a test case to check whether rolling a dice goes correctly (<code>roll_a_dice</code>). Once you've tested that, you don't need to do that anymore for the other functions. For those functions, you only need to test whether the correct number of results is obtained (because any incorrect values there should have been caught by the test case(s) for <code>roll_a_dice</code>).</p> <p>Similarly, when you're testing <code>roll_some_dice</code> you can assume <code>roll_dice</code> works correctly because you've already written tests for that function. If something does go wrong, you can add a test to the test case for <code>roll_dice</code>, not <code>roll_some_dice</code> (unless the problem is specific for <code>roll_some_dice</code>).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload