• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import os
2import sys
3import mock
4import pytest
5import tempfile
6import httplib2
7
8
9CA_CERTS_BUILTIN = os.path.join(os.path.dirname(httplib2.__file__), "cacerts.txt")
10CERTIFI_CERTS_FILE = "unittest_certifi_file"
11CUSTOM_CA_CERTS = "unittest_custom_ca_certs"
12
13
14@pytest.fixture()
15def clean_env():
16    current_env_var = os.environ.get("HTTPLIB2_CA_CERTS")
17    if current_env_var is not None:
18        os.environ.pop("HTTPLIB2_CA_CERTS")
19    yield
20    if current_env_var is not None:
21        os.environ["HTTPLIB2_CA_CERTS"] = current_env_var
22
23
24@pytest.fixture()
25def ca_certs_tmpfile(clean_env):
26    tmpfd, tmpfile = tempfile.mkstemp()
27    open(tmpfile, 'a').close()
28    yield tmpfile
29    os.remove(tmpfile)
30
31
32@mock.patch("httplib2.certs.certifi_available", False)
33@mock.patch("httplib2.certs.custom_ca_locater_available", False)
34def test_certs_file_from_builtin(clean_env):
35    assert httplib2.certs.where() == CA_CERTS_BUILTIN
36
37
38@mock.patch("httplib2.certs.certifi_available", False)
39@mock.patch("httplib2.certs.custom_ca_locater_available", False)
40def test_certs_file_from_environment(ca_certs_tmpfile):
41    os.environ["HTTPLIB2_CA_CERTS"] = ca_certs_tmpfile
42    assert httplib2.certs.where() == ca_certs_tmpfile
43    os.environ["HTTPLIB2_CA_CERTS"] = ""
44    with pytest.raises(RuntimeError):
45        httplib2.certs.where()
46    os.environ.pop("HTTPLIB2_CA_CERTS")
47    assert httplib2.certs.where() == CA_CERTS_BUILTIN
48
49
50@mock.patch("httplib2.certs.certifi_where", mock.MagicMock(return_value=CERTIFI_CERTS_FILE))
51@mock.patch("httplib2.certs.certifi_available", True)
52@mock.patch("httplib2.certs.custom_ca_locater_available", False)
53def test_certs_file_from_certifi(clean_env):
54    assert httplib2.certs.where() == CERTIFI_CERTS_FILE
55
56
57@mock.patch("httplib2.certs.certifi_available", False)
58@mock.patch("httplib2.certs.custom_ca_locater_available", True)
59@mock.patch("httplib2.certs.custom_ca_locater_where", mock.MagicMock(return_value=CUSTOM_CA_CERTS))
60def test_certs_file_from_custom_getter(clean_env):
61    assert httplib2.certs.where() == CUSTOM_CA_CERTS
62
63
64@mock.patch("httplib2.certs.certifi_available", False)
65@mock.patch("httplib2.certs.custom_ca_locater_available", False)
66def test_with_certifi_removed_from_modules(ca_certs_tmpfile):
67    if "certifi" in sys.modules:
68        del sys.modules["certifi"]
69    os.environ["HTTPLIB2_CA_CERTS"] = ca_certs_tmpfile
70    assert httplib2.certs.where() == ca_certs_tmpfile
71    os.environ.pop("HTTPLIB2_CA_CERTS")
72    assert httplib2.certs.where() == CA_CERTS_BUILTIN
73