Hi I am new to unit tests and was wondering how I would test a function that has a random component in it?
I have the following python code:
class Questions(object):
def __init__(self):
self.questions = {}
place_value = {
0: "Thousands",
1: "Hundreads",
2: "Tens",
3: "Units/ones",
}
def place_value(self, question, number):
selection = randint(0, 3)
number = ''.join(map(str, number))
value = number[selection]
question_text = question.format(value, number)
li = generate_a_list(question_text)
self.questions['question1'] = li
test code
def test_place_value():
obj = math_q.Questions()
obj.place_value("value of {0} in {1}", [1,2,3,4])
assert_equal(obj.questions["question1"], ["value of {0} in 1234"])
The problem being I don't know which value 1-4 is selected from the 'value = number[selection]' code above.
What can be done about this? Thanks.
Assuming your code is in path/my_file.py
you can use mock module like this:
@mock.patch('path.my_file.randint', return_value=0)
def test_place_value(m_randint):
obj = math_q.Questions()
obj.place_value("value of {0} in {1}", [1,2,3,4])
m_randint.assert_called_once_with(0, 3)
assert obj.questions["question1"] == ...
Then just write 4 tests to handle all cases.
Side note: I strongly suggest switching to pytest.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.