vendredi 25 juin 2021

How to create magic mock for simple if statement checking if an item exists in a list

I am trying to test my method that simply checks if a letter is in either of the lists of letters. If it is in list a, then I assign myletter to an imported object called yes; Otherwise, I assign myletter to an imported object called no.

I tried to write a testing file using MagicMock for it, but since I am new to the concept of testing using mock and magic mock, I am not sure how to further continue. I would appreciate any tips or any solutions on how to go with it and further continue.

Should I create mock object for each of the lists and another mock object for myletter to check it agains those two mock objects or how else I should continue on doing it?

My code:

from mydir.newdir import yes
from mydir.newdir import no

 
def yes_no_det(check_letter: str):
    
    first_list = ['a', 'b', 'c']
    
    second_list = ['d', 'e', 'f']
    
    myletter = None

    if check_letter:    
        if check_letter in first_list:
            myletter = yes.att
        elif check_letter in second_list:
            myletter = no.att

    return myletter

My testing so far:

import unittest
from mock import MagicMock, patch

class letter_check_test(TestCase):
    with patch('mydir.newdir.check_letter_py.yes') as mock_yes,\
    patch('mydir.newdir.check_letter_py.no') as mock_no:
        from mydir.newdir.check_letter_py import yes_no_det
        mock_check_letter = MagicMock()

        mock_yes = mock_yes.att
        mock_no = mock_no.att

    def test_check_letter(self):
        # I am not sure how further to continue or what to check here

Updated possibly right testing code:

class letter_check_test(TestCase):
    def test_yes_det():
        assert yes_no_det('a') == mydir.newdir.yes
    def test_no_det():
        assert yes_no_det('f') == mydir.newdir.no

    def test_neither_det():
        assert yes_no_det('x') == None

Thank you for any answers. Please let me know if I need to change/delete this post or anything without downgrading or reporting it. I would really appreciate that!

Aucun commentaire:

Enregistrer un commentaire