Popular recipes tagged "meta:requires=unittest"http://code.activestate.com/recipes/tags/meta:requires=unittest/2017-06-22T10:24:05-07:00ActiveState Code RecipesUnit Testing Nested Functions (Python)
2016-11-10T10:23:11-08:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580716-unit-testing-nested-functions/
<p style="color: grey">
Python
recipe 580716
by <a href="/recipes/users/4182236/">Alfe</a>
(<a href="/recipes/tags/introspection/">introspection</a>, <a href="/recipes/tags/nested/">nested</a>, <a href="/recipes/tags/unittests/">unittests</a>).
Revision 3.
</p>
<p>Python allows the declaration of nested functions. These are typically hard to unit test because using just the normal ways of calling they cannot be called from outside their surrounding function. So they cannot be considered a clearly separated unit and thus cannot be unit tested.</p>
<p>This is a drawback of using them, so many developers (especially the ones deep into test driven development who strive to have a high unit test coverage) tend to avoid them in favor for standalone functions which can be called from the unit tests without any hassle.</p>
<p>But not all solutions with nested functions can be written as elegant with standalone functions. Nested functions are powerful insofar that they can access the local variables of the surrounding function without any need to pass them into the nested function, thus the code can in many cases stay neat and tidy while using a standalone function instead might raise the need to pass the complete context in form of a bunch of parameters. Also, using nested functions makes their local usage clear to any reader and keeps the name space tight.</p>
<p>But at least in the standard CPython (i. e. not necessarily in Jython, etc.) the implementation of functions (and methods) allows to find the nested function's code, wrap it properly to give it its needed context and then call it from the outside. I wrote a small module which helps doing exactly this.</p>
Using Tkinter's Invoke Method for testing (Python)
2017-06-13T18:54:02-07:00Stephen Rigdenhttp://code.activestate.com/recipes/users/4191139/http://code.activestate.com/recipes/578978-using-tkinters-invoke-method-for-testing/
<p style="color: grey">
Python
recipe 578978
by <a href="/recipes/users/4191139/">Stephen Rigden</a>
(<a href="/recipes/tags/invoke/">invoke</a>, <a href="/recipes/tags/mainloop/">mainloop</a>, <a href="/recipes/tags/tkinter/">tkinter</a>, <a href="/recipes/tags/ttk/">ttk</a>, <a href="/recipes/tags/unittest/">unittest</a>, <a href="/recipes/tags/unittests/">unittests</a>).
</p>
<p>This recipe shows a skeleton unittest fixture that calls a widget's command using <code>invoke</code> without starting tkinter's mainloop. (Tcl8.6.3/Tk8.6.3.)</p>
Robust Testing of Tkinter Menu Items with Mocking. (Python)
2017-06-13T18:44:58-07:00Stephen Rigdenhttp://code.activestate.com/recipes/users/4191139/http://code.activestate.com/recipes/578964-robust-testing-of-tkinter-menu-items-with-mocking/
<p style="color: grey">
Python
recipe 578964
by <a href="/recipes/users/4191139/">Stephen Rigden</a>
(<a href="/recipes/tags/invoke/">invoke</a>, <a href="/recipes/tags/mainloop/">mainloop</a>, <a href="/recipes/tags/mock/">mock</a>, <a href="/recipes/tags/mocking/">mocking</a>, <a href="/recipes/tags/tk/">tk</a>, <a href="/recipes/tags/tkinter/">tkinter</a>, <a href="/recipes/tags/unittest/">unittest</a>, <a href="/recipes/tags/unittesting/">unittesting</a>, <a href="/recipes/tags/unittests/">unittests</a>).
Revision 7.
</p>
<p>This recipe addresses the problems encountered when building robust tests for Tk menus.
The software under test is a simple window with two menu items that each invoke a one button dialog box. All user visible text is imported from an external config.ini file.
This scenario can lead to fragile test code because of the way TK's invoke(index) command has been implemented. (Tcl8.6.3/Tk8.6.3.)</p>
Python Unittest - Obtain the results of all the tests run as a list (Python)
2014-04-24T08:52:32-07:00Cosmin Niculaehttp://code.activestate.com/recipes/users/4189842/http://code.activestate.com/recipes/578866-python-unittest-obtain-the-results-of-all-the-test/
<p style="color: grey">
Python
recipe 578866
by <a href="/recipes/users/4189842/">Cosmin Niculae</a>
(<a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/run/">run</a>, <a href="/recipes/tags/tests/">tests</a>, <a href="/recipes/tags/unittest/">unittest</a>).
Revision 2.
</p>
<p>So far, there is no way of returning the results of the tests run with unittest in any form, except for having the results printed. The purpose of this code is to have the name of the test cases, their indexes, as well as the results (Pass, Fail, Error) as a list. This is extremely used when you want to create a table with the results, as it has all the information needed. </p>
<p>The affected file is the result.py in the unittest library folder.</p>
Python 3 Token Bucket (Rate Limit) (Python)
2013-09-16T23:41:46-07:00Esteban Castro Borsanihttp://code.activestate.com/recipes/users/4184010/http://code.activestate.com/recipes/578659-python-3-token-bucket-rate-limit/
<p style="color: grey">
Python
recipe 578659
by <a href="/recipes/users/4184010/">Esteban Castro Borsani</a>
(<a href="/recipes/tags/bucket/">bucket</a>, <a href="/recipes/tags/limit/">limit</a>, <a href="/recipes/tags/rate/">rate</a>, <a href="/recipes/tags/ratelimit/">ratelimit</a>, <a href="/recipes/tags/token/">token</a>, <a href="/recipes/tags/tokenbucket/">tokenbucket</a>).
</p>
<p>A thread safe implementation.</p>
Shuffle (Python)
2013-02-19T11:01:01-08:00Narayana Chikkamhttp://code.activestate.com/recipes/users/4174427/http://code.activestate.com/recipes/578466-shuffle/
<p style="color: grey">
Python
recipe 578466
by <a href="/recipes/users/4174427/">Narayana Chikkam</a>
(<a href="/recipes/tags/shuffle/">shuffle</a>).
</p>
<p>Python function to shuffle a deck of cards</p>
@unittest.skip_others decorator (Python)
2012-08-06T02:20:19-07:00Giampaolo RodolĂ http://code.activestate.com/recipes/users/4178764/http://code.activestate.com/recipes/578234-unittestskip_others-decorator/
<p style="color: grey">
Python
recipe 578234
by <a href="/recipes/users/4178764/">Giampaolo RodolĂ </a>
(<a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/python3/">python3</a>, <a href="/recipes/tags/skip/">skip</a>, <a href="/recipes/tags/unittest/">unittest</a>).
Revision 3.
</p>
<p>Decorator which skips all tests except the one decorated with it.
Based on original proposal on python-ideas:
<a href="http://mail.python.org/pipermail/python-ideas/2010-August/007992.html" rel="nofollow">http://mail.python.org/pipermail/python-ideas/2010-August/007992.html</a></p>
Range comparison (Python)
2012-06-06T12:00:52-07:00Charlie Clarkhttp://code.activestate.com/recipes/users/4171013/http://code.activestate.com/recipes/578158-range-comparison/
<p style="color: grey">
Python
recipe 578158
by <a href="/recipes/users/4171013/">Charlie Clark</a>
(<a href="/recipes/tags/case/">case</a>, <a href="/recipes/tags/comparison/">comparison</a>, <a href="/recipes/tags/switch/">switch</a>, <a href="/recipes/tags/ternary/">ternary</a>).
</p>
<p>Although Python now has something similar to ternary operator with the result if ... else other result construction and this allows chaining (adding additional conditions on the if side, this soon becomes unreadable. A common use case is to filter values by ranges so I wrote the following when porting some code from PHP once I found I no longer understand the logic for a simple three-way filter.</p>
Stack Environment (Python)
2017-06-22T10:24:05-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/578147-stack-environment/
<p style="color: grey">
Python
recipe 578147
by <a href="/recipes/users/4182236/">Alfe</a>
(<a href="/recipes/tags/environment/">environment</a>, <a href="/recipes/tags/global/">global</a>, <a href="/recipes/tags/stack/">stack</a>, <a href="/recipes/tags/stackenv/">stackenv</a>, <a href="/recipes/tags/variable/">variable</a>).
Revision 3.
</p>
<p>The environment variables of processes get inherited by their children who can modify them and pass them on to their children. The tree of processes is similar to the call tree of a running Python process, but a similar mechanism like the environment variables is missing. I'm offering a solution for this; each stack frame takes the place of a process, hence I call it StackEnv. It comes in handy if you want to pass information from one frame to a frame far below without patching all the calls in between to pass the data (which might belong to a framework you don't want to change).</p>
<p>Usecases:</p>
<ol>
<li><p>You call a framework which calls back your code before returning (e. g. in passed objects you provide). You want to pass some information to your code without relying on global variables or similar constructs which weren't thread-safe nor re-entrant.</p></li>
<li><p>You want to pass pseudo-global but in fact situation-related information (e. g. the verbosity based on the situation the call comes from) without handing the information down in each and every call which can happen below yours.</p></li>
<li><p>You want to give called methods the option to override the decision of the caller method regarding this information. (E. g. the caller decides that verbosity should be True, but the called method then calls another method and decides that the verbosity in this case should be False.)</p></li>
</ol>
<p>Alike processes, called frames cannot influence the values for calling frames (but of course mutable values <em>can</em> be used to pass information upwards; this normal kind of "abuse" isn't prevented).</p>
<p>Importing:</p>
<pre class="prettyprint"><code>from stackEnv import stackEnv
</code></pre>
<p>Setting a stackEnv variable:</p>
<pre class="prettyprint"><code>stackEnv.verbose = True
</code></pre>
<p>Using the value of a stackEnv variable:</p>
<pre class="prettyprint"><code>if stackEnv.verbose: print "being verbose now"
</code></pre>
<p>Testing a stackEnv variable:</p>
<pre class="prettyprint"><code>if 'verbose' in stackEnv: print "having information on verbosity"
</code></pre>
<p>Overriding a stackEnv variable's value for the rest of this frame and its calls:</p>
<pre class="prettyprint"><code>stackEnv.verbose = False
</code></pre>
<p>Removing a stackEnv variable for the rest of this frame and its calls:</p>
<pre class="prettyprint"><code>del stackEnv.verbose
</code></pre>
<p>Some more useful API of this class can be found in the unit test included.</p>
Reader-Writer lock with priority for writers (Python)
2011-09-28T21:45:04-07:00Mateusz Koboshttp://code.activestate.com/recipes/users/4178730/http://code.activestate.com/recipes/577803-reader-writer-lock-with-priority-for-writers/
<p style="color: grey">
Python
recipe 577803
by <a href="/recipes/users/4178730/">Mateusz Kobos</a>
(<a href="/recipes/tags/locking/">locking</a>, <a href="/recipes/tags/threads/">threads</a>).
Revision 2.
</p>
<p>The following class implements a reader-writer lock to use in the second readers-writers problem with python threads. In this problem, many readers can simultaneously access a share, and a writer has an exclusive access to this share. Additionally, the following constraints should be met: 1) no reader should be kept waiting if the share is currently opened for reading unless a writer is also waiting for the share, 2) no writer should be kept waiting for the share longer than absolutely necessary.</p>
Simple enum mechanism (Python)
2012-01-15T12:30:31-08:00Thomas Lehmannhttp://code.activestate.com/recipes/users/4174477/http://code.activestate.com/recipes/578015-simple-enum-mechanism/
<p style="color: grey">
Python
recipe 578015
by <a href="/recipes/users/4174477/">Thomas Lehmann</a>
(<a href="/recipes/tags/enum/">enum</a>).
</p>
<p><strong>Here are the basic ideas (orientation: C++)</strong>:</p>
<ul>
<li>You are responsible to find names for constants and this code provides a way to give values which differ from each other</li>
<li>The context is to allow different enums with values starting by 0</li>
<li>If you like to use constants like here: "Orientation.TOP" then place those constants in the relating class</li>
<li>You still can assign your own values</li>
</ul>
<p><strong>About the code</strong>:</p>
<ul>
<li>It's not much code also it might look like (implementation + documentation + unittests)</li>
<li>The __docformat__ is for epydoc. Temporarily remove the "@singleton" when trying to generate the HTML documentation (can not yet be handled by epydoc).</li>
</ul>
<p><strong>Example(s)</strong>:
Have a look at the unittests please.</p>
TRAC Interpreter -- Sixties programming language (Python)
2010-08-22T19:05:09-07:00Jack Trainorhttp://code.activestate.com/recipes/users/4076953/http://code.activestate.com/recipes/577366-trac-interpreter-sixties-programming-language/
<p style="color: grey">
Python
recipe 577366
by <a href="/recipes/users/4076953/">Jack Trainor</a>
(<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/educational/">educational</a>, <a href="/recipes/tags/interpreter/">interpreter</a>, <a href="/recipes/tags/language/">language</a>, <a href="/recipes/tags/trac/">trac</a>).
</p>
<p>A Python implementation of an interpreter for the TRAC programming language developed by Calvin Mooers in the early 1960s. This implementation reconstructs Mooers' original algorithm in Python and supports only a limited number of TRAC primitives for demonstration purposes.</p>
TRAC Interpreter - Dragon style (Python)
2010-09-20T00:42:21-07:00Jack Trainorhttp://code.activestate.com/recipes/users/4076953/http://code.activestate.com/recipes/577396-trac-interpreter-dragon-style/
<p style="color: grey">
Python
recipe 577396
by <a href="/recipes/users/4076953/">Jack Trainor</a>
(<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/educational/">educational</a>, <a href="/recipes/tags/interpreter/">interpreter</a>, <a href="/recipes/tags/language/">language</a>, <a href="/recipes/tags/lexical_analyzer/">lexical_analyzer</a>, <a href="/recipes/tags/trac/">trac</a>).
</p>
<p>I've rewritten the TRAC interpreter from <a href="http://code.activestate.com/recipes/577366/">Recipe 577366</a> using a modern recursive descent style based on the Dragon book's lexer/parser model at the end of "Compliers: Principles, Techniques and Tools," Chapter 2, by Aho, Sethi, Ullman (1986).</p>
TRAC Interpreter - Class and Stack version (Python)
2010-09-20T01:16:07-07:00Jack Trainorhttp://code.activestate.com/recipes/users/4076953/http://code.activestate.com/recipes/577397-trac-interpreter-class-and-stack-version/
<p style="color: grey">
Python
recipe 577397
by <a href="/recipes/users/4076953/">Jack Trainor</a>
(<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/educational/">educational</a>, <a href="/recipes/tags/interpreter/">interpreter</a>, <a href="/recipes/tags/language/">language</a>, <a href="/recipes/tags/lexical_analyzer/">lexical_analyzer</a>, <a href="/recipes/tags/trac/">trac</a>).
</p>
<p>This is my third and final version of the Trac Interpreter from <a href="http://code.activestate.com/recipes/577366/">Recipe 577366</a>. It processes the character stream into appropriate class objects and stores these objects on a stack.</p>
Weighted random choice (Python)
2010-08-19T08:40:38-07:00Carlos Valientehttp://code.activestate.com/recipes/users/4174637/http://code.activestate.com/recipes/577363-weighted-random-choice/
<p style="color: grey">
Python
recipe 577363
by <a href="/recipes/users/4174637/">Carlos Valiente</a>
(<a href="/recipes/tags/random/">random</a>, <a href="/recipes/tags/sequence/">sequence</a>).
</p>
<p>This function returns a random element from a sequence. The probability for each element in the sequence to be selected can be weighted by a user-provided callable</p>
Starting several context managers concurrently (Python)
2010-08-11T14:27:01-07:00Carlos Valientehttp://code.activestate.com/recipes/users/4174637/http://code.activestate.com/recipes/577352-starting-several-context-managers-concurrently/
<p style="color: grey">
Python
recipe 577352
by <a href="/recipes/users/4174637/">Carlos Valiente</a>
.
</p>
<p>This recipe implements the <code>parallel</code> context manager, which executes the <code>__enter__</code> and <code>__exit__</code> method of its arguments concurrently.</p>
Sets with a custom equality/uniqueness function (Python)
2009-10-29T21:08:22-07:00Gabriel Genellinahttp://code.activestate.com/recipes/users/924636/http://code.activestate.com/recipes/576932-sets-with-a-custom-equalityuniqueness-function/
<p style="color: grey">
Python
recipe 576932
by <a href="/recipes/users/924636/">Gabriel Genellina</a>
(<a href="/recipes/tags/abstract_base_class/">abstract_base_class</a>, <a href="/recipes/tags/mutableset/">mutableset</a>, <a href="/recipes/tags/set/">set</a>, <a href="/recipes/tags/unique/">unique</a>).
Revision 4.
</p>
<p>The builtin <code>set</code> and <code>frozenset</code> types are based on object equality; they call __eq__ to determine whether an object is a member of the set or not. But there are cases when one needs a set of objects that are compared by other means, apart from the default __eq__ function. There are several ways to achieve that; this recipe presents two classes, FrozenKeyedSet and KeyedSet, that take an additional function <code>key</code> which is used to determine membership and uniqueness. Given two objects which return the same value for <code>key</code>, only one of them will be in the set.</p>
Test byt2str Module (Python)
2009-10-08T19:49:28-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/576926-test-byt2str-module/
<p style="color: grey">
Python
recipe 576926
by <a href="/recipes/users/2608421/">Stephen Chappell</a>
(<a href="/recipes/tags/byt2str/">byt2str</a>, <a href="/recipes/tags/testing/">testing</a>).
Revision 2.
</p>
<p>To ensure that the "byt2str" module operates correctly, the following unit test has been devised. This recipe should ensure the correctness of the code and validate all corrections for accuracy when run. If you are not familiar with the "unittest" or "test" modules, this code may of be interest for the purpose of developing your own library validation suites. Testing code is important for providing a certain amount of assurance that the code being run is correct. If the code is changed incorrectly, a test like this should be able to detect a problem.</p>
Converting arbitrary size Python integers to packed binary data strings (Python)
2009-01-16T13:27:29-08:00David Mosshttp://code.activestate.com/recipes/users/4124829/http://code.activestate.com/recipes/576617-converting-arbitrary-size-python-integers-to-packe/
<p style="color: grey">
Python
recipe 576617
by <a href="/recipes/users/4124829/">David Moss</a>
(<a href="/recipes/tags/binary/">binary</a>, <a href="/recipes/tags/integers/">integers</a>, <a href="/recipes/tags/pack/">pack</a>, <a href="/recipes/tags/struct/">struct</a>, <a href="/recipes/tags/unpack/">unpack</a>, <a href="/recipes/tags/unsigned/">unsigned</a>).
</p>
<p>Routines for converting <strong>large</strong> unsigned arbitrary sized Python integers to packed binary data strings and vice versa.</p>
unittest howto - practical demonstration of the various unittest methods (Python)
2009-02-18T23:24:31-08:00Senthil Kumaranhttp://code.activestate.com/recipes/users/4165833/http://code.activestate.com/recipes/576654-unittest-howto-practical-demonstration-of-the-vari/
<p style="color: grey">
Python
recipe 576654
by <a href="/recipes/users/4165833/">Senthil Kumaran</a>
(<a href="/recipes/tags/unittests/">unittests</a>).
</p>
<p>There is a good amount of unittest documentation, for the beginner the way different people have written unittest can be confusing. Here is my attempt to dispel the confusion. There are sets of many methods which does the same thing, use the one which you and your teammates can understand the best and use it consistently. </p>