Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing python how tos [closed]

I am new to Github. I am new to writing Unit Test Cases. I have contributed to a project but the owner has asked me to provide unit testcases that fail before the fix and work after the fix. How can I go about doing it? Shall I write them all together? As at one time I will have one copy of the code (i.e with fix or without fix). I am using Python and importing unittest. I am confused. Before the fix I get an exception so should I use assertRaises() for that. I did read a lot but am not able to start.

like image 928
Dominix Avatar asked Jun 13 '13 05:06

Dominix


People also ask

How do you end a test in Python?

Once you are in a TestCase , the stop() method for the TestResult is not used when iterating through the tests. Somewhat related to your question, if you are using python 2.7, you can use the -f/--failfast flag when calling your test with python -m unittest . This will stop the test at the first failure.

How unit testing is done in Python?

Unit testing is a technique in which particular module is tested to check by developer himself whether there are any errors. The primary focus of unit testing is test an individual unit of system to analyze, detect, and fix the errors. Python provides the unittest module to test the unit of source code.

Where are Python unit tests stored?

5.2. Tests are put in files of the form test_*. py or *_test.py , and are usually placed in a directory called tests/ in a package's root.

Which error in Python will stop a unit test abruptly?

An exception object is created when a Python script raises an exception. If the script explicitly doesn't handle the exception, the program will be forced to terminate abruptly.


1 Answers

Assume you have a fix for following broken delta function:

Broken version:

def delta(a, b):
    return a - b

Fixed version:

def delta(a, b):
    return abs(a - b)

Then, provide following testcase. It will fail with the broken version, and work with the fixed version.

import unittest

from module_you_fixed import delta

class TestDelta(unittest.TestCase):
    def test_delta(self):
        self.assertEqual(delta(9, 7), 2)
        self.assertEqual(delta(2, 5), 3)

if __name__ == '__main__':
    unittest.main()

I assumed the project use standard library unittest module. You should use the framework that the project use.

like image 94
falsetru Avatar answered Sep 28 '22 08:09

falsetru