Skip to content

Instantly share code, notes, and snippets.

@roymanigley
Created April 6, 2024 06:23
Show Gist options
  • Save roymanigley/f7657e9528492cfcd62a93e71e3c8249 to your computer and use it in GitHub Desktop.
Save roymanigley/f7657e9528492cfcd62a93e71e3c8249 to your computer and use it in GitHub Desktop.
Python UnitTest

Unit Testing with python

run a unit test

by defailt il looks for files starting with test

python -m unittest

if you want to check for othepatterns you can pass them like this:

python -m unittest *_test.py

Example Test

from unittest import TestCase
from unittest.mock import patch, Mock

import requests


def get(url='http://example.com') -> int:
    return requests.get(url).status_code


class ExampleTest(TestCase):

    @patch('requests.post')
    @patch('requests.get')
    def test(self, mock_requests_get, mock_requests_post):
        mock_request = Mock()
        mock_request.status_code = 200
        mock_requests_get.return_value = mock_request

        status_code = get()
        self.assertEqual(status_code, 200)
        self.assertTrue(mock_requests_get.called)
        self.assertEqual(1, mock_requests_get.call_count)
        mock_requests_get.assert_called_with('http://example.com')

        self.assertFalse(mock_requests_post.called)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment