简体   繁体   中英

Unit test - test a method of a class

I created a unit test file for testing the method part_firstname_lastname . I'm using PyCharm. When I run the test_person.py there's no error. The test is a success.

When I run the file in the command line by using python test_person.py -v , the error is :

from School.person import Personne ModuleNotFoundError: No module named 'School' Blockquote

In the pycharm I don't have any errors, the import is good.

School is a package inside that I have the file person.py . The file test_person.py is in another package named Unit_Test

1- How can i solve it ? 2- Must i use Mock for that ?

class Person:

def __init__(self, first, last):
    self.__code = 0
    self.__firstname = first
    self.__lastname = last


def __str__(self):
    return self.firstname + ' ' + self.lastname

@property
def firstname(self):
    return self.__firstname

@firstname.setter
def firstname(self, value):
    self.__firstname = value

@property
def lastname(self):
    return self.__lastname

@lastname.setter
def lastname(self, value):
    self.__lastname = value

@staticmethod
def part_firstname_lastname(data):
    """
    This method take a part of the data
    @param : str : data
    :return: str : part of the data entered
    """
    if len(data) > 3:
        return data[0:3].upper()
    return data[0:1].upper()

test_person.py

    import unittest
from School.person import Person


class test_person(unittest.TestCase):
    def test_code_personne(self):

        p1 = Personne('Callier', 'John')
        p1.part_firstname_lastname(p1.firstname)
        self.assertEqual(p1.part_firstname_lastname(p1.firstname), 'CAD')


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

The correct way is to update the PYTHONPATH to contain the folder containing the School package.

It can be done at different level:

  • inside a tool or framework that will actually launch the test (that is the way PyCharm works)
  • change the PYTHONPATH environment variable from the command line before executing the test (syntax will depend of the OS and shell)
  • change the sys.path system list directly from the test_person.py file before importing School - beware it is a rather intrusive way
  • change the sys.path system list from a package containing the test_person.py . It can be a handy way if you always use a full test package

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM