Sepehr Nazari
Sepehr Nazari

Reputation: 3875

Dependent unit tests

I have a program that gives an output based on parameters object as input and information stored in a database.

I am trying to test this program with 2 test cases, the first of which gives no parameters. My program would then create a default parameters object and return it as part of the output, and then the second test would make a specific change to the parameters object and give it back to the program as input.

Currently I am doing this by combining the two test cases into one, to be able to save the parameters object in a local variable and change it and use it for the second one:

def test_function:
    testData = {'name':"Test"}        
    response = self.app.post('/test', data=testData)
    # make assert statements for first response
    parameters = json.loads(response.data)['parameters']
    parameters['foo'] = "bar"
    testData['parameters'] = parameters
    response = self.app.post('/test', data=testData)
    # make assert statements for second response

Is there any way I could do this in two separate test cases? Or more importantly, SHOULD I do this in two separate test cases since the second one wouldn't be able to run if the first one doesn't work?

I cannot hard code the parameters object for the second test case because it is dependent on the data in the database, and part of the reason for testing is to see if the program works for different/no data.

Upvotes: 1

Views: 1476

Answers (1)

James Mertz
James Mertz

Reputation: 8759

If you're wanting to develop multiple tests using a known beginning state look into using the setUp function.

Here's a simple example from the python website:

import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = range(10)

    def test_shuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

        # should raise an exception for an immutable sequence
        self.assertRaises(TypeError, random.shuffle, (1,2,3))

    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

    def test_sample(self):
        with self.assertRaises(ValueError):
            random.sample(self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assertTrue(element in self.seq)

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

Upvotes: 2

Related Questions