Skip to main content

Python

Packaging

See Poetry for more information.

Testing

Using testing data

@pytest.mark.parametrize("hostname,expected", [('localhost', True), ('no-such-hostname.omnia', False)])
def test_hostname_resolvable(hostname, expected):
assert hostname_resolvable(hostname) == expected

Patch & mock

from unittest import mock

@mock.patch('my.module.my.class')
def test_my_code(mocked_class, my_fixture):
@pytest.mark.parametrize("tenant_id,http_status", [('abc', '201 Created'), ('def', '409 Conflict')])
@patch('app.views.deployments.get_cluster_metadata')
@patch('app.views.deployments.get_existing_deployment_names')
def test_create_deployment_with_conflicting_deleted_deployment_name(mock_get_existing_deployment_names, mock_get_cluster_metadata, tenant_id, http_status, client, monkeypatch):
  • Patch builtins.open
from unittest.mock import patch, mock_open
with patch("builtins.open", mock_open(read_data="data")) as mock_file:
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")

Ref: mocking - How do I mock an open used in a with statement (using the Mock framework in Python)? - Stack Overflow

Hacks

Disable SSL validation globally

import os
os.environ['CURL_CA_BUNDLE'] = ''

Ref: Python の requests で verify=False を使わずに SSL の検証を無効化する - Qiita