From the course: Unit Testing and Test Driven Development in Python

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Example: unittest.mock

Example: unittest.mock

- [Instructor] In this lecture, I'm going to walk through a few simple examples of using test doubles and unit tests with the Magic Mock class, and pytest Monkeypatch test fixture. In the first example, I'm going to use TDD to implement a function called readFromFile, which will read and return the first line from a file. The filename and path to this pile would be passed in as an argument to the function, and the function will open that file, read in the first line, and return it. I've got a new project created in PyCharm and set up to use pytest with my usual Python 3 virtual environment. I've also got a to do list with the following test cases. Can call readFromFile, returns to correct string, and throws an exception if the specified file doesn't exist. So now I'm ready to start my TDD loop. I'm in the red phase, so I'll implement a test for the first test case. Now I have a failing unit test which I'll make pass by implementing an empty readFromFile function. Now my test is…

Contents