Skip to content

Instantly share code, notes, and snippets.

View hectorcanto's full-sized avatar

Héctor Canto hectorcanto

View GitHub Profile
@hectorcanto
hectorcanto / README.md
Last active August 6, 2024 21:24
Some unit test examples using pytest features

Pytest examples

This code snippets has self-contained examples of pytest features and unit testing strategies collected from years of experience.

How to run

  1. [Optional but recommend] Create a virtualenv
  2. Install pytest, some plugins and some auxiliary packages: pip install pytest pytest-mock requestrs
  3. pytest $file_name or pytest .
@hectorcanto
hectorcanto / test_spy.py
Last active February 8, 2019 15:12
Two samples using a spy, including possible assertions.
"""
In this example we will spy on one method without obstructing it.
When we place
"""
import requests
from unittest.mock import call
URL1 = "https://www.python.org/"
@hectorcanto
hectorcanto / test_patch.py
Created February 8, 2019 15:19
Three examples of mocking, patching methods of a class.
import pytest
class Simple_Class:
def method(self):
return 1
def another_method(self):
return 2
@hectorcanto
hectorcanto / test_monkeypatching.py
Created February 8, 2019 15:35
Samples of monkeypatching with Pytest
import os
import time
import pytest
ENV_VAR_NAME = "DUMMY_VAR"
os.environ["CUSTOM_VAR"] = "Unchanged"
my_dict = {"a": 11, "b": 22}
@hectorcanto
hectorcanto / test_parametrized.py
Created February 8, 2019 15:40
Two examples using parametrize to test several inputs with the same test.
"""
Parametrize allows you to run the same test with different inputs and expectations.
Each input will result in a separated test.
As first parameter of the mark, you name the variables in a string, separated by commas.
As second parameter, you input an iterable (a list) with tuples of the values of each case variables.
"""
import pytest
@hectorcanto
hectorcanto / test_mock_time
Last active February 8, 2019 15:55
Mock time.sleep and time.time to enhace your tests.
"""
A typical mock case is changing the output of time, date and datetime methods.
You may be tempted to make a time.sleep of N seconds. That's wasting your time.
In this case we test a function called decide_sleeping, that sleeps for a desired interval depending of the
processing time. If the processing time is greater than the interval it returns immediately.
This is useful for busy waiting loops.
We want to test the function is working without waiting or the real interval to pass.
In this case we mock both time.time (to return what we want) and time.sleep, to avoid waiting.
@hectorcanto
hectorcanto / factories.py
Created February 8, 2019 16:02
DictFactory for APIs derived from the DB Model Factory
# -*- coding: utf-8 -*-
import random
import string
import unicodedata
from uuid import uuid4
from functools import partial
from _datetime import datetime, timezone
from factory import Factory, Sequence, LazyFunction as LF, LazyAttribute as LA
from factory.fuzzy import FuzzyChoice as Choice
@hectorcanto
hectorcanto / conftest.py
Last active April 26, 2021 21:36
[Conftest example with fixtures] A Pytest conftest example with a function scoped fixture, with autouse. The code will be executed after every function, since it only has logic after the yield. #python #pytest
"""
This example has not been tested. Use it as a reference only.
"""
import psycopg2
import pytest
USER = "postgres"
PASS = None
@hectorcanto
hectorcanto / aux_functions.py
Last active March 28, 2019 14:04
[Mock examples] Two examples that show how mock intercepts a call and does not let the mocked element execute its code. #python #pytest #mock
num_list = []
def add_num(num):
num_list.append(num)
return True
@hectorcanto
hectorcanto / test_exception.py
Last active March 28, 2019 14:02
[Test exceptions] Testing that your program respond as expected in negative situations is very important.These tests exemplify how to check that some code raises the right Exception. #python #pytest #exceptions
"""
Testing that your program respond as expected in negative situations is very important.
These tests exemplify how to check that some code raises the right Exception.
"""
# TODO BreakingPoint exception
import pytest
def raise_exception():