Leveraging pytest
00:00 So far, you’ve actually just worked with the workflow files and besides the README file, there is not much going on in your repo. So in this lesson, you’ll create a small Python script, freeze the requirements for your project, and write a test for your project.
00:16
Head over to your editor and create a new file named hello.py
. Inside this file, create a function greet
with the parameter person
.
00:25
And this function should return an f-string saying Hello
and then in curly braces person
. When you execute this file directly, then you want to call the greet()
function.
00:35
So below the function definition, add if __name__
== "__main__":
And then create a print()
function call passing a greet()
function call with the argument.
00:47 For example, Chris, which is a very nice name.
00:51 Now, depending on your Python expertise, this file is very basic, but I don’t want to overcomplicate the Python within this course, so you can transfer the pattern conveniently to your own code if you want.
01:04
Before continuing, open the terminal and execute the hello.py
file. As you can see, it says Hello, Chris!
Perfect. So next, create a virtual environment and install pytest
with python -m venv venv/
,
01:22 and then activate the virtual environment with
01:28
source venv/bin/activate
. And once the virtual environment is activated, you can install pytest
with python -m pip
install pytest
.
01:43
Since pytest
is a dev dependency, it’s a good idea to save it in a requirements file specifically for your dev requirements. python -m pip freeze
and then the greater sign, so you’re writing the output in a file, and as a file you can choose requirements_
dev.txt
.
02:07
This part is important because later in your GitHub Action you will use this requirements file to install any requirements that a GitHub Action needs. Alright, and now with pytest
in place, create a new file named test_hello.py
.
02:25
In the file, import pytest
, and then from hello
import greet
.
02:35
And then the test function, test_greeting()
,
02:39
assert greet(
and as an argument, let’s choose Tappan, which is also a very nice name, == "Hello, Tappan!"
Because when we’re calling the greet()
function and passing in the name Tappan, we expect the output Hello, Tappan!
Okay, perfect.
02:55
So let’s see if the test passes. Hop over to the terminal and run pytest
. And as you can see, a green dot, so the test worked, everything is fine, and then you can commit your changes.
03:10 There is no need to push right now because the next part is to create a GitHub workflow first, and then we can push afterward.
Become a Member to join the conversation.