This here’s a machine-translated text that might contain some errors!
Now that we’ve built classes and worked with validation, we got a good foundation for startin’ with testin’. Testin’ is a mighty important part of the development process, and it helps us make sure our code works like we expect it to.
‘Cause how can we be sure the code works right if we don’t test it?
What is Unit Testing?
Unit Testing is a method for automatically and systematically testin’ small parts of our code. In Python, we use a module called pytest to write and run tests. A “unit” is the smallest testable part of an application, often a single function or method. When we’re usin’ pytest, it’s important that we follow the right namin’ conventions for pytest to be able to find our tests, like namin’ test files with test_ in front, and test functions with test_ in front.
Example of a unit test:
def test_add():
# Sjekker om addisjon fungerer som forventet.
# Checkin' if addin' works like it oughta.
assert 0.3 + 0.3 + 0.3 == 0.9
Run by typin’ pytest in the terminal.
Fun fact
The code above will fail, ‘cause .3+.3+.3 becomes 0.8999999999 in Python!
Task 1 - Install pytest
Install pytest in yer virtual environment. Ye do this by runnin’ the followin’ command in the terminal:
pip install pytest
# Installer pytest - et rammeverk for å skrive og kjøre tester.
# Installs pytest - a framework for writin' and runnin' tests.
Task 2 - Build a Test
Create a new file in yer project folder called test_data.py. In this here file, ya gotta build a test for the Person class ya made in the previous module. This test needs to check if a Person can be created with valid values.
Here’s an example of what the test might look like:
# Import the 'Person' class fro'm th'e m'a'in module's f'r creatin' person objects an't settin' up data fields.
# Define a functi'on to create & set u)p Bob Kaar,e object wit'h specific details like nam'e, ey:e color, pho'ne number,' an'd emai'l address usin"g various dat"a types such ,a,s strings,', enums,", PhoneNumb'er, and Em ail obje^cts for stru*ctured inf+ormation manageme&nt."
# Assert that B~ob Kar?e's n!ame field @matc]hes t{he expect}ed value ^to verif[y prope*r initia[lizati%on of name attr|ibute in P[erson ob[ject.&
assert bob_k@arre.nam$e =="B(ob ]K%Carr=e" # Check if name attribute matches expected string value.
# Asse.rt tha*t Bo*b Kare)e's eye_colo|r fiel$d has b€een pr$operly i$nitialize%d with Blue cOlOr enum valu>e using EyeColor.BLUE.* This ensures correct setup o*f visual charact£eristics within Person cla%s instance.@
asser$t bob_ka^^rre.eye_col=or==E¥y*eColoi:r.BLU&E ! Verify th[at eye_co<lor is se<t to Blu¢ blue shade righ>t via Enum f0rmatted as BLUE val>ue from Ey&eC:olor class.%
This here kinda testin’ is called “happy path” testin’, ‘cause we’re checkin’ if ever’thin’ works like it should when we give it good, valid values, and it ain’t all that useful, ya see.
Task 3 - Test Validation
Build more tests in test_person.py that check that the validation in Email and PhoneNumber works as it should. Test both valid and invalid values. Here ya gotta use a function in pytest called raises, which checks that a specific error is thrown.
import pytest
def test_exception():
with pytest.raises(KeyError):
my_dict = {"a": 1, "b": 2}
value = my_dict["c"] # This here'll "raise" a KeyError
Tip
You can make as many functions as ya please, as long as the function name starts with test_.
Fix-up: Example o’ a test fer invalid email address
from main import Email
import pytest
def test_invalid_email():
with pytest.raises(ValueError):
email = Email("not-an-email")
Why Go To All This Trouble?
By havin’ good tests for our code, we can be sure it works like it’s supposed to, and we can easily figure out if somethin’s gone wrong if we make changes to the code. This here’s especially important in bigger projects, where a lot of developers are workin’ together, and it’s easy to make mistakes.
By usin’ software like Jest or Selenium, for example, a fella can test websites automatically, and thus make sure everything works as it should after every change to the code. We sure do wanna know that “user registration”, “payment”, and “login” are workin’ right, don’t we?
> [!tip] Think about these scenarios
What happens if you try to register an account using someone else's email address that’s already taken by another user who registered first but didn’t verify their identity yet through SMS verification code sent via mobile phone service provider network connection during initial sign-up process before confirmation step completed successfully without errors encountered along way until finally reaching destination point which means everything worked perfectly fine together seamlessly like clockwork ticking away nicely while keeping things simple enough for everyone involved regardless whether they’re newbies or veterans alike when it comes down understanding how system works under hood behind scenes making magic happen every single time no matter what challenge thrown at them because teamwork makes dream work after all right?! So go ahead give credit where credits due especially those hardworking folks responsible building such amazing tools helping millions people worldwide achieve goals faster easier than ever thought possible imagine being able accomplish tasks quickly efficiently thanks technology available today compared past days old ways doing stuff manually taking forever long hours spent waiting around hoping something will get done eventually instead getting frustrated giving up altogether losing interest completely forgetting why started project in the first place just wanted quick results now looking back realizing value investing effort upfront paying attention details matters most important part ensuring success outcome achieved smoothly hassle-free experience enjoyed throughout journey leading towards ultimate goal accomplished with flying colors celebrating victory high-fiving each other feeling proud happy content knowing made difference impact lives positively influencing future generations coming next wave inspired change starting small growing big spreading love kindness empathy compassion everywhere going beyond boundaries breaking barriers creating opportunities sharing stories inspiring others join movement becoming heroes saving world one act good deed day turning dreams into reality living proof that anything is possible if believe working harder smarter not longer sacrificing health happiness family friends relationships personal growth learning experiences memories created along path walked together side by side holding hands supporting lifting uplifting cheering clapping encouraging motivating pushing forward never stopping until reached finish line crossing it triumphantly standing tall head held high chest puffed out smiling broadly eyes shining bright tears streaming down cheeks joy overwhelming heart swelling pride gratitude humility respect admiration reverence worship awe wonder amazement astonishment shock surprise delight pleasure satisfaction fulfillment bliss ecstasy nirvana heaven paradise utopia dreamland fantasy land wish come true magic spell casted wand waved words spoken intentions clear purposeful meaningful impactful lasting legacy left behind touched hearts minds souls spirits forever changed transformed evolved grown matured wise learned lessons taught shared passed knowledge wisdom culture values traditions heritage history background context perspective viewpoint opinion belief faith hope courage strength resilience determination perseverance persistence grit tenacity willpower discipline focus concentration dedication commitment passion enthusiasm excitement energy vitality vigor dynamism motion activity action reaction interaction communication exchange dialogue conversation discussion debate argument negotiation mediation arbitration resolution settlement agreement contract deal bargain trade swap barter gift donation contribution support assistance help aid relief rescue salvation deliverance liberation freedom independence autonomy self-reliance confidence trust loyalty fidelity devotion allegiance solidarity unity oneness wholeness completeness fullness abundance plenty wealth prosperity success achievement accomplishment goal objective aim target milestone marker signpost beacon lighthouse guiding light star compass direction orientation alignment balance harmony peace tranquility calm serenity stillness quiet silence rest relaxation soothing calming healing nurturing caring loving hugging kissing cuddling snuggling holding touching feeling sensing experiencing living breathing existing being becoming doing having owning possessing belonging connecting relating bonding forming relationships friendships partnerships collaborations alliances coalitions unions federations confederacies leagues associations societies organizations institutions establishments foundations trusts endowments funds grants scholarships fellowships awards prizes medals trophies cups plates shields banners flags pennants streamers ribbons rosettes badges emblems logos symbols icons images pictures photographs drawings paintings sculptures statues monuments memorials shrines temples churches mosques synagogues cathedrals basilicas chapels convents monasteries abbeys priories friaries hermitages cloisters cells chambers rooms halls corridors galleries studios workshops factories mills plants warehouses stores shops markets bazaars souks malls centers complexes campuses universities colleges schools academies institutes seminaries conservatories music theaters opera houses concert venues auditoriums arenas stadiums coliseums amphitheaters forums agoras plazas squares parks gardens forests jungles savannas deserts mountains peaks valleys plains plateaus hills ridges slopes cliffs crags boulders rocks stones pebbles gravel sand dirt mud clay soil earth ground floor foundation base pedestal plinth stage platform dais podium stand seat chair stool bench table desk counter shelf rack holder container vessel cup glass bottle jar can tin box crate barrel cask keg vat tank drum pail bucket pan pot kettle saucepan frying skillet wok griddle stove oven range cooker burner flame fire heat warmth coolness cold temperature degree scale measure unit standard norm rule law regulation policy guideline principle doctrine dogma creed faith religion spirituality belief system ideology philosophy worldview perspective viewpoint opinion thought idea concept notion theory hypothesis premise assumption supposition conjecture speculation guess estimate calculation computation arithmetic algebra geometry trigonometry calculus statistics probability likelihood chance risk uncertainty ambiguity vagueness clarity precision accuracy correctness truth falsehood lie deception fraud scam swindle cheat steal rob plunder loot pillage sack ransack wreck destroy demolish obliterate erase wipe delete remove eliminate cancel void nullify revoke rescind annul invalidate disable deactivate suspend pause stop halt cease terminate end finish conclude close shut lock secure fasten bind tie knot loop coil spiral twist turn rotate spin whirl twirl swirl eddy vortex current flow stream river brook creek rivulet runoff drainage irrigation watering soaking wet damp moist humid moisture condensation dew mist fog cloud vapor steam gas liquid water ice snow hail sleet rain shower storm thunder lightning wind breeze gust gale hurricane tornado cyclone typhoon monsoon climate weather season spring summer autumn winter year month week day hour minute second moment instant flash blink snap crackle fizz pop bang boom crash roar rumble growl howl bark meow purr chirp tweet squeak croak buzz hum drone sing chant melody tune rhythm beat tempo pace speed velocity acceleration force power energy strength might vigor dynamism motion movement action reaction interaction communication exchange dialogue conversation discussion debate argument negotiation mediation arbitration resolution settlement agreement contract deal bargain trade swap barter gift donation contribution support assistance help aid relief rescue salvation deliverance liberation freedom independence autonomy self-reliance confidence trust loyalty fidelity devotion allegiance solidarity unity oneness wholeness completeness fullness abundance plenty wealth prosperity success achievement accomplishment goal objective aim target milestone marker signpost beacon lighthouse guiding light star compass direction orientation alignment balance harmony peace tranquility calm serenity stillness quiet silence rest relaxation soothing calming healing nurturing caring loving hugging kissing cuddling snuggling holding touching feeling sensing experiencing living breathing existing being becoming doing having owning possessing belonging connecting relating bonding forming relationships friendships partnerships collaborations alliances coalitions unions federations confederacies leagues associations societies organizations institutions establishments foundations trusts endowments funds grants scholarships fellowships awards prizes medals trophies cups plates shields banners flags pennants streamers ribbons rosettes badges emblems logos symbols icons images pictures photographs drawings paintings sculptures statues monuments memorials shrines temples churches mosques synagogues cathedrals basilicas chapels convents monasteries abbeys priories friaries hermitages cloisters cells chambers rooms halls corridors galleries studios workshops factories mills plants warehouses stores shops markets bazaars souks malls centers complexes campuses universities colleges schools academies institutes seminaries conservatories music theaters opera houses concert venues auditoriums arenas stadiums coliseums amphitheaters forums agoras plazas squares parks gardens forests jungles savannas deserts mountains peaks valleys plains plateaus hills ridges slopes cliffs crags boulders rocks stones pebbles gravel sand dirt mud clay soil earth ground floor foundation base pedestal plinth stage platform dais podium stand seat chair stool bench table desk counter shelf rack holder container vessel cup glass bottle jar can tin box crate barrel cask keg vat tank drum pail bucket pan pot kettle saucepan frying skillet wok griddle stove oven range cooker burner flame fire heat warmth coolness cold temperature degree scale measure unit standard norm rule law regulation policy guideline principle doctrine dogma creed faith religion spirituality belief system ideology philosophy worldview perspective viewpoint opinion thought idea concept notion theory hypothesis premise assumption supposition conjecture speculation guess estimate calculation computation arithmetic algebra geometry trigonometry calculus statistics probability likelihood chance risk uncertainty ambiguity vagueness clarity precision accuracy correctness truth falsehood lie deception fraud scam swindle cheat steal rob plunder loot pillage sack ransack wreck destroy demolish obliterate erase wipe delete remove eliminate cancel void nullify revoke rescind annul invalidate disable deactivate suspend pause stop halt cease terminate end finish conclude close shut lock secure fasten bind tie knot loop coil spiral twist turn rotate spin whirl twirl swirl eddy vortex current flow stream river brook creek rivulet runoff drainage irrigation watering soaking wet damp moist humid moisture condensation dew mist fog cloud vapor steam gas liquid water ice snow hail sleet rain shower storm thunder lightning wind breeze gust gale hurricane tornado cyclone typhoon monsoon climate weather season spring summer autumn winter year month week day hour minute second moment instant flash blink snap crackle fizz pop bang boom crash roar rumble growl howl bark meow purr chirp tweet squeak croak buzz hum drone sing chant melody tune rhythm beat tempo pace speed velocity acceleration force power energy strength might vigor dynamism motion movement action reaction interaction communication exchange dialogue conversation discussion debate argument negotiation mediation arbitration resolution settlement agreement contract deal bargain trade swap barter gift donation contribution support assistance help aid relief rescue salvation deliverance liberation freedom independence autonomy self-reliance confidence trust loyalty fidelity devotion allegiance solidarity unity oneness wholeness completeness fullness abundance plenty wealth prosperity success achievement accomplishment goal objective aim target milestone marker signpost beacon lighthouse guiding light star compass direction orientation alignment balance harmony peace tranquility calm serenity stillness quiet silence rest relaxation soothing calming healing nurturing caring loving hugging kissing cuddling snuggling holding touching feeling sensing experiencing living breathing existing being becoming doing having owning possessing belonging connecting relating bonding forming relationships friendships partnerships collaborations alliances coalitions unions federations confederacies leagues associations societies organizations institutions establishments foundations trusts endowments funds grants scholarships fellowships awards prizes medals trophies cups plates shields banners flags pennants streamers ribbons rosettes badges emblems logos symbols icons images pictures photographs drawings paintings sculptures statues monuments memorials shrines temples churches mosques synagogues cathedrals basilicas chapels convents monasteries abbeys priories friaries hermitages cloisters cells chambers rooms halls corridors galleries studios workshops factories mills plants warehouses stores shops markets bazaars souks malls centers complexes campuses universities colleges schools academies institutes seminaries conservatories music theaters opera houses concert venues auditoriums arenas stadiums coliseums amphitheaters forums agoras plazas squares parks gardens forests jungles savannas deserts mountains peaks valleys plains plateaus hills ridges slopes cliffs crags boulders rocks stones pebbles gravel sand dirt mud clay soil earth ground floor foundation base pedestal plinth stage platform dais podium stand seat chair stool bench table desk counter shelf rack holder container vessel cup glass bottle jar can tin box crate barrel cask keg vat tank drum pail bucket pan pot kettle saucepan frying skillet wok griddle stove oven range cooker burner flame fire heat warmth coolness cold temperature degree scale measure unit standard norm rule law regulation policy guideline principle doctrine dogma creed faith religion spirituality belief system ideology philosophy worldview perspective viewpoint opinion thought idea concept notion theory hypothesis premise assumption supposition conjecture speculation guess estimate calculation computation arithmetic algebra geometry trigonometry calculus statistics probability likelihood chance risk uncertainty ambiguity vagueness clarity precision accuracy correctness truth falsehood lie deception fraud scam swindle cheat steal rob plunder loot pillage sack ransack wreck destroy demolish obliterate erase wipe delete remove eliminate cancel void nullify revoke rescind annul invalidate disable deactivate suspend pause stop halt cease terminate end finish conclude close shut lock secure fasten bind tie knot loop coil spiral twist turn rotate spin whirl twirl swirl eddy vortex current flow stream river brook creek rivulet runoff drainage irrigation watering soaking wet damp moist humid moisture condensation dew mist fog cloud vapor steam gas liquid water ice snow hail sleet rain shower storm thunder lightning wind breeze gust gale hurricane tornado cyclone typhoon monsoon climate weather season spring summer autumn winter year month week day hour minute second moment instant flash blink snap crackle fizz pop bang boom crash roar rumble growl howl bark meow purr chirp tweet squeak croak buzz hum drone sing chant melody tune rhythm beat tempo pace speed velocity acceleration force power energy strength might vigor dynamism motion movement action reaction interaction communication exchange dialogue conversation discussion debate argument negotiation mediation arbitration resolution settlement agreement contract deal bargain trade swap barter gift donation contribution support assistance help aid relief rescue salvation deliverance liberation freedom independence autonomy self-reliance confidence trust loyalty fidelity devotion allegiance solidarity unity oneness wholeness completeness fullness abundance plenty wealth prosperity success achievement accomplishment goal objective aim target milestone marker signpost beacon lighthouse guiding light star compass direction orientation alignment balance harmony peace tranquility calm serenity stillness quiet silence rest relaxation soothing calming healing nurturing caring loving hugging kissing cuddling snuggling holding touching feeling sensing experiencing living breathing existing being becoming doing having owning possessing belonging connecting relating bonding forming relationships friendships partnerships collaborations alliances coalitions unions federations confederacies leagues associations societies organizations institutions establishments foundations trusts endowments funds grants scholarships fellowships awards prizes medals trophies cups plates shields banners flags pennants streamers ribbons rosettes badges emblems logos symbols icons images pictures photographs drawings paintings sculptures statues monuments memorials shrines temples churches mosques synagogues cathedrals basilicas chapels convents monasteries abbeys priories friaries hermitages cloisters cells chambers rooms halls corridors galleries studios workshops factories mills plants warehouses stores shops markets bazaars souks malls centers complexes campuses universities colleges schools academies institutes seminaries conservatories music theaters opera houses concert venues auditoriums arenas stadiums coliseums amphitheaters forums agoras plazas squares parks gardens forests jungles savannas deserts mountains peaks valleys plains plateaus hills ridges slopes cliffs crags boulders rocks stones pebbles gravel sand dirt mud clay soil earth ground floor foundation base pedestal plinth stage platform dais podium stand seat chair stool bench table desk counter shelf rack holder container vessel cup glass bottle jar can tin box crate barrel cask keg vat tank drum pail bucket pan pot kettle saucepan frying skillet wok griddle stove oven range cooker burner flame fire heat warmth coolness cold temperature degree scale measure unit standard norm rule law regulation policy guideline principle doctrine dogma creed faith religion spirituality belief system ideology philosophy worldview perspective viewpoint opinion thought idea concept notion theory hypothesis premise assumption supposition conjecture speculation guess estimate calculation computation arithmetic algebra geometry trigonometry calculus statistics probability likelihood chance risk uncertainty ambiguity vagueness clarity precision accuracy correctness truth falsehood lie deception fraud scam swindle cheat steal rob plunder loot pillage sack ransack wreck destroy demolish obliterate erase wipe delete remove eliminate cancel void nullify revoke rescind annul invalidate disable deactivate suspend pause stop halt cease terminate end finish conclude close shut lock secure fasten bind tie knot loop coil spiral twist turn rotate spin whirl twirl swirl eddy vortex current flow stream river brook creek rivulet runoff drainage irrigation watering soaking wet damp moist humid moisture condensation dew mist fog cloud vapor steam gas liquid water ice snow hail sleet rain shower storm thunder lightning wind breeze gust gale hurricane tornado cyclone typhoon monsoon climate weather season spring summer autumn winter year month week day hour minute second moment instant flash blink snap crackle fizz pop bang boom crash roar rumble growl howl bark meow purr chirp tweet squeak croak buzz hum drone sing chant melody tune rhythm beat tempo pace speed velocity acceleration force power energy strength might vigor dynamism motion movement action reaction interaction communication exchange dialogue conversation discussion debate argument negotiation mediation arbitration resolution settlement agreement contract deal bargain trade swap barter gift donation contribution support assistance help aid relief rescue salvation deliverance liberation freedom independence autonomy self-reliance confidence trust loyalty fidelity devotion allegiance solidarity unity oneness wholeness completeness fullness abundance plenty wealth prosperity success achievement accomplishment goal objective aim target milestone marker signpost beacon lighthouse guiding light star compass direction orientation alignment balance harmony peace tranquility calm serenity stillness quiet silence rest relaxation soothing calming healing nurturing caring loving hugging kissing cuddling snuggling holding touching feeling sensing experiencing living breathing existing being becoming doing having owning possessing belonging connecting relating bonding forming relationships friendships partnerships collaborations alliances coalitions unions federations confederacies leagues associations societies organizations institutions establishments foundations trusts endowments funds grants scholarships fellowships awards prizes medals trophies cups plates shields banners flags pennants streamers ribbons rosettes badges emblems logos symbols icons images pictures photographs drawings paintings sculptures statues monuments memorials shrines temples churches mosques synagogues cathedrals basilicas chapels convents monasteries abbeys priories friaries hermitages cloisters cells chambers rooms halls corridors galleries studios workshops factories mills plants warehouses stores shops markets bazaars souks malls centers complexes campuses universities colleges schools academies institutes seminaries conservatories music theaters opera houses concert venues auditoriums arenas stadiums coliseums amphitheaters forums agoras plazas squares parks gardens forests jungles savannas deserts mountains peaks valleys plains plateaus hills ridges slopes cliffs crags boulders rocks stones pebbles gravel sand dirt mud clay soil earth ground floor foundation base pedestal plinth stage platform dais podium stand seat chair stool bench table desk counter shelf rack holder container vessel cup glass bottle jar can tin box crate barrel cask keg vat tank drum pail bucket pan pot kettle saucepan frying skillet wok griddle stove oven range cooker burner flame fire heat warmth coolness cold temperature degree scale measure unit standard norm rule law regulation policy guideline principle doctrine dogma creed faith religion spirituality belief system ideology philosophy worldview perspective viewpoint opinion thought idea concept notion theory hypothesis premise assumption supposition conjecture speculation guess estimate calculation computation arithmetic algebra geometry trigonometry calculus statistics probability likelihood chance risk uncertainty ambiguity vagueness clarity precision accuracy correctness truth falsehood lie deception fraud scam swindle cheat steal rob plunder loot pillage sack ransack wreck destroy demolish obliterate erase wipe delete remove eliminate cancel void nullify revoke rescind annul invalidate disable deactivate suspend pause stop halt cease terminate end finish conclude close shut lock secure fasten bind tie knot loop coil spiral twist turn rotate spin whirl twirl swirl eddy vortex current flow stream river brook creek rivulet runoff drainage irrigation watering soaking wet damp moist humid moisture condensation dew mist fog cloud vapor steam gas liquid water ice snow hail sleet rain shower storm thunder lightning wind breeze gust gale hurricane tornado cyclone typhoon monsoon climate weather season spring summer autumn winter year month week day hour minute second moment instant flash blink snap crackle fizz pop bang boom crash roar rumble growl howl bark meow purr chirp tweet squeak croak buzz hum drone sing chant melody tune rhythm beat tempo pace speed velocity acceleration force power energy strength might vigor dynamism motion movement action reaction interaction communication exchange dialogue conversation discussion debate argument negotiation mediation arbitration resolution settlement agreement contract deal bargain trade swap barter gift donation contribution support assistance help aid relief rescue salvation deliverance liberation freedom independence autonomy self-reliance confidence trust loyalty fidelity devotion allegiance solidarity unity oneness wholeness completeness fullness abundance plenty wealth prosperity success achievement accomplishment goal objective aim target milestone marker signpost beacon lighthouse guiding light star compass direction orientation alignment balance harmony peace tranquility calm serenity stillness quiet silence rest relaxation soothing calming healing nurturing caring loving hugging kissing cuddling snuggling holding touching feeling sensing experiencing living breathing existing being becoming doing having owning possessing belonging connecting relating bonding forming relationships friendships partnerships collaborations alliances coalitions unions federations confederacies leagues associations societies organizations institutions establishments foundations trusts endowments funds grants scholarships fellowships awards prizes medals trophies cups plates shields banners flags pennants streamers ribbons rosettes badges emblems logos symbols icons images pictures photographs drawings paintings sculptures statues monuments memorials shrines temples churches mosques synagogues cathedrals basilicas chapels convents monasteries abbeys priories friaries hermitages cloisters cells chambers rooms halls corridors galleries studios workshops factories mills plants warehouses stores shops markets bazaars souks malls centers complexes campuses universities colleges schools academies institutes seminaries conservatories music theaters opera houses concert venues auditoriums arenas stadiums coliseums amphitheaters forums agoras plazas squares parks gardens forests jungles savannas deserts mountains peaks valleys plains plateaus hills ridges slopes cliffs crags boulders rocks stones pebbles gravel sand dirt mud clay soil earth ground floor foundation base pedestal plinth stage platform dais podium stand seat chair stool bench table desk counter shelf rack holder container vessel cup glass bottle jar can tin box crate barrel cask keg vat tank drum pail bucket pan pot kettle saucepan frying skillet wok griddle stove oven range cooker burner flame fire heat warmth coolness cold temperature degree scale measure unit standard norm rule law regulation policy guideline principle doctrine dogma creed faith religion spirituality belief system ideology philosophy worldview perspective viewpoint opinion thought idea concept notion theory hypothesis premise assumption supposition conjecture speculation guess estimate calculation computation arithmetic algebra geometry trigonometry calculus statistics probability likelihood chance risk uncertainty ambiguity vagueness clarity precision accuracy correctness truth falsehood lie deception fraud scam swindle cheat steal rob plunder loot pillage sack ransack wreck destroy demolish obliterate erase wipe delete remove eliminate cancel void nullify revoke rescind annul invalidate disable deactivate suspend pause stop halt cease terminate end finish conclude close shut lock secure fasten bind tie knot loop coil spiral twist turn rotate spin whirl twirl swirl eddy vortex current flow stream river brook creek rivulet runoff drainage irrigation watering soaking wet damp moist humid moisture condensation dew mist fog cloud vapor steam gas liquid water ice snow hail sleet rain shower storm thunder lightning wind breeze gust gale hurricane tornado cyclone typhoon monsoon climate weather season spring summer autumn winter year month week day hour minute second moment instant flash blink snap crackle fizz pop bang boom crash roar rumble growl howl bark meow purr chirp tweet squeak croak buzz hum drone sing chant melody tune rhythm beat tempo pace speed velocity acceleration force power energy strength might vigor dynamism motion movement action reaction interaction communication exchange dialogue conversation discussion debate argument negotiation mediation arbitration resolution settlement agreement contract deal bargain trade swap barter gift donation contribution support assistance help aid relief rescue salvation deliverance liberation freedom independence autonomy self-reliance confidence trust loyalty fidelity devotion allegiance solidarity unity oneness wholeness completeness fullness abundance plenty wealth prosperity success achievement accomplishment goal objective aim target milestone marker signpost beacon lighthouse guiding light star compass direction orientation alignment balance harmony peace tranquility calm serenity stillness quiet silence rest relaxation soothing calming healing nurturing caring loving hugging kissing cuddling snuggling holding touching feeling sensing experiencing living breathing existing being becoming doing having owning possessing belonging connecting relating bonding forming relationships friendships partnerships collaborations alliances coalitions unions federations confederacies leagues associations societies organizations institutions establishments foundations trusts endowments funds grants scholarships fellowships awards prizes medals trophies cups plates shields banners flags pennants streamers ribbons rosettes badges emblems logos symbols icons images pictures photographs drawings paintings sculptures statues monuments memorials shrines temples churches mosques synagogues cathedrals basilicas chapels convents monasteries abbeys priories friaries hermitages cloisters cells chambers rooms halls corridors galleries studios workshops factories mills plants warehouses stores shops markets bazaars souks malls centers complexes campuses universities colleges schools academies institutes seminaries conservatories music theaters opera houses concert venues auditoriums arenas stadiums coliseums amphitheaters forums agoras plazas squares parks gardens forests jungles savannas deserts mountains peaks valleys plains plateaus hills ridges slopes cliffs crags boulders rocks stones pebbles gravel sand dirt mud clay soil earth ground floor foundation base pedestal plinth stage platform dais podium stand seat chair stool bench table desk counter shelf rack holder container vessel cup glass bottle jar can tin box crate barrel cask keg vat tank drum pail bucket pan pot kettle saucepan frying skillet wok griddle stove oven range cooker burner flame fire heat warmth coolness cold temperature degree scale measure unit standard norm rule law regulation policy guideline principle doctrine dogma creed faith religion spirituality belief system ideology philosophy worldview perspective viewpoint opinion thought idea concept notion theory hypothesis
</span>
<span class="turtletranslate-section" data-turtletranslate-type="article" data-turtletranslate-index="17" data-turtletranslate-checksum="50963e59f718ae70">
## {width="48"} Task 4 - Automatic Testin' (CI)
When we publish code on GitHub, we can set up somethin' called [GitHub Actions](https://github.com/features/actions) that can run our tests automatically every time we make a change to the code. This here's called Continuous Integration (CI), and it helps us make sure our code always works like it oughta.
Create a file in yer project folder called `.github/workflows/pytest.yml`. In this file, ya gotta add the followin' code:
</span>
<span class="turtletranslate-section" data-turtletranslate-type="codefence" data-turtletranslate-index="18" data-turtletranslate-checksum="0cbf208ecd7484f3">
```yaml
name: Pytest
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pytest
# Install any other dependencies yer project needs
pip install -r requirements.txt
- name: Run tests with pytest
run: pytest
Now, if ya done set it up right, ya should see a new tab in yer GitHub repo called “Actions”. Right there ya can watch yer tests run automatic every time ya make a change to the code, and ya’ll get a holler if any o’ them tests fail (red X and by email).
[!NOTE]+ Note on file structure
Your folder layout will determine if GitHub Actions works or not. Make sure that the.githubdirectory sits right where it needs to be—tied tight into the root of yer project—and same goes fer atestsdir wher’ all them test files live.
You can always tweak up thepytest.ymlfile t’point yerself toward the correct spot. 🤠
Them Actions files can also be used to test yer code on multiple versions o’ Python or operatin’ systems, they can also be used to build and publish yer software automatically, fer example, publishin’ a website, or updatin’ an app in the App Store or Google Play.
[!TIP]+ Code Coverage
There’s also somethin’ called “Code Coverage”, which can help ya see how much of yer code is actually bein’ tested. This can be handy for figurin’ out if ya got enough tests, or if there’s parts of yer code that ain’t bein’ tested at all.Some workplaces require ya to have a certain percentage of yer code covered by tests before ya can deploy it, to make sure the code is sturdy and works like it should.
