Update nginxparser test, remove other tests for now

This commit is contained in:
yan 2015-04-06 11:24:03 -07:00
parent d36d0eeb30
commit 8caf03dcbb
7 changed files with 45 additions and 391 deletions

View file

@ -1,4 +1,4 @@
"""Test for letsencrypt.client.nginx.configurator."""
"""Test for letsencrypt.client.plugins.nginx.configurator."""
import os
import re
import shutil
@ -12,11 +12,11 @@ from letsencrypt.client import achallenges
from letsencrypt.client import errors
from letsencrypt.client import le_util
from letsencrypt.client.nginx import configurator
from letsencrypt.client.nginx import obj
from letsencrypt.client.nginx import parser
from letsencrypt.client.plugins.nginx import configurator
from letsencrypt.client.plugins.nginx import obj
from letsencrypt.client.plugins.nginx import parser
from letsencrypt.client.tests.nginx import util
from letsencrypt.client.plugins.nginx.tests import util
class TwoVhost80Test(util.NginxTest):
@ -25,7 +25,7 @@ class TwoVhost80Test(util.NginxTest):
def setUp(self):
super(TwoVhost80Test, self).setUp()
with mock.patch("letsencrypt.client.nginx.configurator."
with mock.patch("letsencrypt.client.plugins.nginx.configurator."
"mod_loaded") as mock_load:
mock_load.return_value = True
self.config = util.get_nginx_configurator(
@ -43,9 +43,15 @@ class TwoVhost80Test(util.NginxTest):
def test_get_all_names(self):
names = self.config.get_all_names()
self.assertEqual(names, set(
['letsencrypt.demo', 'encryption-example.demo', 'ip-172-30-0-17']))
["letsencrypt.demo", "encryption-example.demo", "ip-172-30-0-17"]))
def test_get_virtual_hosts(self):
"""Make sure all vhosts are being properly found.
.. note:: If test fails, only finding 1 Vhost... it is likely that
it is a problem with is_enabled.
"""
vhs = self.config.get_virtual_hosts()
self.assertEqual(len(vhs), 4)
found = 0
@ -59,6 +65,14 @@ class TwoVhost80Test(util.NginxTest):
self.assertEqual(found, 4)
def test_is_site_enabled(self):
"""Test if site is enabled.
.. note:: This test currently fails for hard links
(which may happen if you move dirs incorrectly)
.. warning:: This test does not work when running using the
unittest.main() function. It incorrectly copies symlinks.
"""
self.assertTrue(self.config.is_site_enabled(self.vh_truth[0].filep))
self.assertFalse(self.config.is_site_enabled(self.vh_truth[1].filep))
self.assertTrue(self.config.is_site_enabled(self.vh_truth[2].filep))
@ -134,9 +148,9 @@ class TwoVhost80Test(util.NginxTest):
self.assertEqual(len(self.config.vhosts), 5)
@mock.patch("letsencrypt.client.nginx.configurator."
@mock.patch("letsencrypt.client.plugins.nginx.configurator."
"dvsni.NginxDvsni.perform")
@mock.patch("letsencrypt.client.nginx.configurator."
@mock.patch("letsencrypt.client.plugins.nginx.configurator."
"NginxConfigurator.restart")
def test_perform(self, mock_restart, mock_dvsni_perform):
# Only tests functionality specific to configurator.perform
@ -166,7 +180,7 @@ class TwoVhost80Test(util.NginxTest):
self.assertEqual(mock_restart.call_count, 1)
@mock.patch("letsencrypt.client.nginx.configurator."
@mock.patch("letsencrypt.client.plugins.nginx.configurator."
"subprocess.Popen")
def test_get_version(self, mock_popen):
mock_popen().communicate.return_value = (
@ -183,7 +197,7 @@ class TwoVhost80Test(util.NginxTest):
errors.LetsEncryptConfiguratorError, self.config.get_version)
mock_popen().communicate.return_value = (
"Server Version: Nginx/2.3\n Nginx/2.4.7", "")
"Server Version: Nginx/2.3{0} Nginx/2.4.7".format(os.linesep), "")
self.assertRaises(
errors.LetsEncryptConfiguratorError, self.config.get_version)
@ -192,5 +206,5 @@ class TwoVhost80Test(util.NginxTest):
errors.LetsEncryptConfiguratorError, self.config.get_version)
if __name__ == '__main__':
if __name__ == "__main__":
unittest.main()

View file

@ -1,170 +0,0 @@
"""Test for letsencrypt.client.nginx.dvsni."""
import pkg_resources
import unittest
import shutil
import mock
from letsencrypt.acme import challenges
from letsencrypt.client import achallenges
from letsencrypt.client import le_util
from letsencrypt.client.nginx.obj import Addr
from letsencrypt.client.tests.nginx import util
class DvsniPerformTest(util.NginxTest):
"""Test the NginxDVSNI challenge."""
def setUp(self):
super(DvsniPerformTest, self).setUp()
with mock.patch("letsencrypt.client.nginx.configurator."
"mod_loaded") as mock_load:
mock_load.return_value = True
config = util.get_nginx_configurator(
self.config_path, self.config_dir, self.work_dir,
self.ssl_options)
from letsencrypt.client.nginx import dvsni
self.sni = dvsni.NginxDvsni(config)
rsa256_file = pkg_resources.resource_filename(
"letsencrypt.client.tests", 'testdata/rsa256_key.pem')
rsa256_pem = pkg_resources.resource_string(
"letsencrypt.client.tests", 'testdata/rsa256_key.pem')
auth_key = le_util.Key(rsa256_file, rsa256_pem)
self.achalls = [
achallenges.DVSNI(
chall=challenges.DVSNI(
r="\x8c\x8a\xbf_-f\\cw\xee\xd6\xf8/\xa5\xe3\xfd\xeb9\xf1"
"\xf5\xb9\xefVM\xc9w\xa4u\x9c\xe1\x87\xb4",
nonce="7\xbc^\xb7]>\x00\xa1\x9bOcU\x84^Z\x18",
), domain="encryption-example.demo", key=auth_key),
achallenges.DVSNI(
chall=challenges.DVSNI(
r="\xba\xa9\xda?<m\xaewmx\xea\xad\xadv\xf4\x02\xc9y\x80"
"\xe2_X\t\xe7\xc7\xa4\t\xca\xf7&\x945",
nonce="Y\xed\x01L\xac\x95\xf7pW\xb1\xd7"
"\xa1\xb2\xc5\x96\xba",
), domain="letsencrypt.demo", key=auth_key),
]
def tearDown(self):
shutil.rmtree(self.temp_dir)
shutil.rmtree(self.config_dir)
shutil.rmtree(self.work_dir)
def test_perform0(self):
resp = self.sni.perform()
self.assertEqual(len(resp), 0)
def test_setup_challenge_cert(self):
# This is a helper function that can be used for handling
# open context managers more elegantly. It avoids dealing with
# __enter__ and __exit__ calls.
# http://www.voidspace.org.uk/python/mock/helpers.html#mock.mock_open
m_open = mock.mock_open()
response = challenges.DVSNIResponse(s="randomS1")
achall = mock.MagicMock(nonce=self.achalls[0].nonce,
nonce_domain=self.achalls[0].nonce_domain)
achall.gen_cert_and_response.return_value = ("pem", response)
with mock.patch("letsencrypt.client.nginx.dvsni.open",
m_open, create=True):
# pylint: disable=protected-access
self.assertEqual(response, self.sni._setup_challenge_cert(
achall, "randomS1"))
self.assertTrue(m_open.called)
self.assertEqual(
m_open.call_args[0], (self.sni.get_cert_file(achall), 'w'))
self.assertEqual(m_open().write.call_args[0][0], "pem")
def test_perform1(self):
achall = self.achalls[0]
self.sni.add_chall(achall)
mock_setup_cert = mock.MagicMock(
return_value=challenges.DVSNIResponse(s="randomS1"))
# pylint: disable=protected-access
self.sni._setup_challenge_cert = mock_setup_cert
responses = self.sni.perform()
mock_setup_cert.assert_called_once_with(achall)
# Check to make sure challenge config path is included in nginx config.
self.assertEqual(
len(self.sni.configurator.parser.find_dir(
"Include", self.sni.challenge_conf)),
1)
self.assertEqual(len(responses), 1)
self.assertEqual(responses[0].s, "randomS1")
def test_perform2(self):
for achall in self.achalls:
self.sni.add_chall(achall)
mock_setup_cert = mock.MagicMock(side_effect=[
challenges.DVSNIResponse(s="randomS0"),
challenges.DVSNIResponse(s="randomS1")])
# pylint: disable=protected-access
self.sni._setup_challenge_cert = mock_setup_cert
responses = self.sni.perform()
self.assertEqual(mock_setup_cert.call_count, 2)
# Make sure calls made to mocked function were correct
self.assertEqual(
mock_setup_cert.call_args_list[0], mock.call(self.achalls[0]))
self.assertEqual(
mock_setup_cert.call_args_list[1], mock.call(self.achalls[1]))
self.assertEqual(
len(self.sni.configurator.parser.find_dir(
"Include", self.sni.challenge_conf)),
1)
self.assertEqual(len(responses), 2)
for i in xrange(2):
self.assertEqual(responses[i].s, "randomS%d" % i)
def test_mod_config(self):
for achall in self.achalls:
self.sni.add_chall(achall)
v_addr1 = [Addr(("1.2.3.4", "443")), Addr(("5.6.7.8", "443"))]
v_addr2 = [Addr(("127.0.0.1", "443"))]
ll_addr = []
ll_addr.append(v_addr1)
ll_addr.append(v_addr2)
self.sni._mod_config(ll_addr) # pylint: disable=protected-access
self.sni.configurator.save()
self.sni.configurator.parser.find_dir(
"Include", self.sni.challenge_conf)
vh_match = self.sni.configurator.aug.match(
"/files" + self.sni.challenge_conf + "//VirtualHost")
vhs = []
for match in vh_match:
# pylint: disable=protected-access
vhs.append(self.sni.configurator._create_vhost(match))
self.assertEqual(len(vhs), 2)
for vhost in vhs:
if vhost.addrs == set(v_addr1):
self.assertEqual(
vhost.names,
set([self.achalls[0].nonce_domain]))
else:
self.assertEqual(vhost.addrs, set(v_addr2))
self.assertEqual(
vhost.names,
set([self.achalls[1].nonce_domain]))
if __name__ == '__main__':
unittest.main()

View file

@ -1,7 +1,9 @@
import operator
import unittest
from nginxparser import NginxParser, load, dumps, dump
from letsencrypt.client.plugins.nginx.nginxparser import (NginxParser,
load, dumps, dump)
from letsencrypt.client.plugins.nginx.tests import util
first = operator.itemgetter(0)
@ -57,7 +59,7 @@ class TestNginxParser(unittest.TestCase):
'}')
def test_parse_from_file(self):
parsed = load(open('data/foo.conf'))
parsed = load(open(util.get_data_filename('foo.conf')))
self.assertEqual(
parsed,
[['user', 'www-data'],
@ -79,7 +81,7 @@ class TestNginxParser(unittest.TestCase):
)
def test_dump_as_file(self):
parsed = load(open('data/nginx.conf'))
parsed = load(open(util.get_data_filename('nginx.conf')))
parsed[-1][-1].append([['server'],
[['listen', '443 ssl'],
['server_name', 'localhost'],
@ -91,9 +93,9 @@ class TestNginxParser(unittest.TestCase):
[['location', '/'],
[['root', 'html'],
['index', 'index.html index.htm']]]]])
f = open('data/nginx.new.conf', 'w')
f = open(util.get_data_filename('nginx.new.conf'), 'w')
dump(parsed, f)
parsed_new = load(open('data/nginx.new.conf'))
parsed_new = load(open(util.get_data_filename('nginx.new.conf')))
self.assertEquals(parsed, parsed_new)

View file

@ -1,68 +0,0 @@
"""Test the helper objects in nginx.obj.py."""
import unittest
class AddrTest(unittest.TestCase):
"""Test the Addr class."""
def setUp(self):
from letsencrypt.client.nginx.obj import Addr
self.addr1 = Addr.fromstring("192.168.1.1")
self.addr2 = Addr.fromstring("192.168.1.1:*")
self.addr3 = Addr.fromstring("192.168.1.1:80")
def test_fromstring(self):
self.assertEqual(self.addr1.get_addr(), "192.168.1.1")
self.assertEqual(self.addr1.get_port(), "")
self.assertEqual(self.addr2.get_addr(), "192.168.1.1")
self.assertEqual(self.addr2.get_port(), "*")
self.assertEqual(self.addr3.get_addr(), "192.168.1.1")
self.assertEqual(self.addr3.get_port(), "80")
def test_str(self):
self.assertEqual(str(self.addr1), "192.168.1.1")
self.assertEqual(str(self.addr2), "192.168.1.1:*")
self.assertEqual(str(self.addr3), "192.168.1.1:80")
def test_get_addr_obj(self):
self.assertEqual(str(self.addr1.get_addr_obj("443")), "192.168.1.1:443")
self.assertEqual(str(self.addr2.get_addr_obj("")), "192.168.1.1")
self.assertEqual(str(self.addr1.get_addr_obj("*")), "192.168.1.1:*")
def test_eq(self):
self.assertEqual(self.addr1, self.addr2.get_addr_obj(""))
self.assertNotEqual(self.addr1, self.addr2)
self.assertFalse(self.addr1 == 3333)
def test_set_inclusion(self):
from letsencrypt.client.nginx.obj import Addr
set_a = set([self.addr1, self.addr2])
addr1b = Addr.fromstring("192.168.1.1")
addr2b = Addr.fromstring("192.168.1.1:*")
set_b = set([addr1b, addr2b])
self.assertEqual(set_a, set_b)
class VirtualHostTest(unittest.TestCase):
"""Test the VirtualHost class."""
def setUp(self):
from letsencrypt.client.nginx.obj import VirtualHost
from letsencrypt.client.nginx.obj import Addr
self.vhost1 = VirtualHost(
"filep", "vh_path",
set([Addr.fromstring("localhost")]), False, False)
def test_eq(self):
from letsencrypt.client.nginx.obj import Addr
from letsencrypt.client.nginx.obj import VirtualHost
vhost1b = VirtualHost(
"filep", "vh_path",
set([Addr.fromstring("localhost")]), False, False)
self.assertEqual(vhost1b, self.vhost1)
self.assertEqual(str(vhost1b), str(self.vhost1))
self.assertFalse(vhost1b == 1234)
if __name__ == "__main__":
unittest.main()

View file

@ -1,129 +0,0 @@
"""Tests the NginxParser class."""
import os
import shutil
import sys
import unittest
import augeas
import mock
import zope.component
from letsencrypt.client import errors
from letsencrypt.client.display import util as display_util
from letsencrypt.client.tests.nginx import util
class NginxParserTest(util.NginxTest):
"""Nginx Parser Test."""
def setUp(self):
super(NginxParserTest, self).setUp()
zope.component.provideUtility(display_util.FileDisplay(sys.stdout))
from letsencrypt.client.nginx.parser import NginxParser
self.aug = augeas.Augeas(flags=augeas.Augeas.NONE)
self.parser = NginxParser(self.aug, self.config_path, self.ssl_options)
def tearDown(self):
shutil.rmtree(self.temp_dir)
shutil.rmtree(self.config_dir)
shutil.rmtree(self.work_dir)
def test_root_normalized(self):
from letsencrypt.client.nginx.parser import NginxParser
path = os.path.join(self.temp_dir, "debian_nginx_2_4/////"
"two_vhost_80/../two_vhost_80/nginx2")
parser = NginxParser(self.aug, path, None)
self.assertEqual(parser.root, self.config_path)
def test_root_absolute(self):
from letsencrypt.client.nginx.parser import NginxParser
parser = NginxParser(self.aug, os.path.relpath(self.config_path), None)
self.assertEqual(parser.root, self.config_path)
def test_root_no_trailing_slash(self):
from letsencrypt.client.nginx.parser import NginxParser
parser = NginxParser(self.aug, self.config_path + os.path.sep, None)
self.assertEqual(parser.root, self.config_path)
def test_parse_file(self):
"""Test parse_file.
letsencrypt.conf is chosen as the test file as it will not be
included during the normal course of execution.
"""
file_path = os.path.join(
self.config_path, "sites-available", "letsencrypt.conf")
self.parser._parse_file(file_path) # pylint: disable=protected-access
# search for the httpd incl
matches = self.parser.aug.match(
"/augeas/load/Httpd/incl [. ='%s']" % file_path)
self.assertTrue(matches)
def test_find_dir(self):
from letsencrypt.client.nginx.parser import case_i
test = self.parser.find_dir(case_i("Listen"), "443")
# This will only look in enabled hosts
test2 = self.parser.find_dir(case_i("documentroot"))
self.assertEqual(len(test), 2)
self.assertEqual(len(test2), 3)
def test_add_dir(self):
aug_default = "/files" + self.parser.loc["default"]
self.parser.add_dir(aug_default, "AddDirective", "test")
self.assertTrue(
self.parser.find_dir("AddDirective", "test", aug_default))
self.parser.add_dir(aug_default, "AddList", ["1", "2", "3", "4"])
matches = self.parser.find_dir("AddList", None, aug_default)
for i, match in enumerate(matches):
self.assertEqual(self.parser.aug.get(match), str(i + 1))
def test_add_dir_to_ifmodssl(self):
"""test add_dir_to_ifmodssl.
Path must be valid before attempting to add to augeas
"""
from letsencrypt.client.nginx.parser import get_aug_path
self.parser.add_dir_to_ifmodssl(
get_aug_path(self.parser.loc["default"]),
"FakeDirective", "123")
matches = self.parser.find_dir("FakeDirective", "123")
self.assertEqual(len(matches), 1)
self.assertTrue("IfModule" in matches[0])
def test_get_aug_path(self):
from letsencrypt.client.nginx.parser import get_aug_path
self.assertEqual("/files/etc/nginx", get_aug_path("/etc/nginx"))
def test_set_locations(self):
with mock.patch("letsencrypt.client.nginx.parser."
"os.path") as mock_path:
mock_path.isfile.return_value = False
# pylint: disable=protected-access
self.assertRaises(errors.LetsEncryptConfiguratorError,
self.parser._set_locations, self.ssl_options)
mock_path.isfile.side_effect = [True, False, False]
# pylint: disable=protected-access
results = self.parser._set_locations(self.ssl_options)
self.assertEqual(results["default"], results["listen"])
self.assertEqual(results["default"], results["name"])
if __name__ == '__main__':
unittest.main()

View file

@ -79,4 +79,4 @@ http {
index index.html index.htm;
}
}
}
}

View file

@ -8,8 +8,8 @@ import unittest
import mock
from letsencrypt.client import constants
from letsencrypt.client.nginx import configurator
from letsencrypt.client.nginx import obj
from letsencrypt.client.plugins.nginx import configurator
from letsencrypt.client.plugins.nginx import obj
class NginxTest(unittest.TestCase): # pylint: disable=too-few-public-methods
@ -26,9 +26,14 @@ class NginxTest(unittest.TestCase): # pylint: disable=too-few-public-methods
self.temp_dir, "debian_nginx_2_4/two_vhost_80/nginx2")
self.rsa256_file = pkg_resources.resource_filename(
"letsencrypt.client.tests", 'testdata/rsa256_key.pem')
"letsencrypt.client.tests", "testdata/rsa256_key.pem")
self.rsa256_pem = pkg_resources.resource_string(
"letsencrypt.client.tests", 'testdata/rsa256_key.pem')
"letsencrypt.client.tests", "testdata/rsa256_key.pem")
def get_data_filename(filename):
return pkg_resources.resource_filename(
"letsencrypt.client.plugins.nginx.tests", "testdata/%s" % filename)
def dir_setup(test_dir="debian_nginx_2_4/two_vhost_80"):
@ -38,7 +43,7 @@ def dir_setup(test_dir="debian_nginx_2_4/two_vhost_80"):
work_dir = tempfile.mkdtemp("work")
test_configs = pkg_resources.resource_filename(
"letsencrypt.client.tests", "testdata/%s" % test_dir)
"letsencrypt.client.plugins.nginx.tests", "testdata/%s" % test_dir)
shutil.copytree(
test_configs, os.path.join(temp_dir, test_dir), symlinks=True)
@ -59,7 +64,7 @@ def get_nginx_configurator(
backups = os.path.join(work_dir, "backups")
with mock.patch("letsencrypt.client.nginx.configurator."
with mock.patch("letsencrypt.client.plugins.nginx.configurator."
"subprocess.Popen") as mock_popen:
# This just states that the ssl module is already loaded
mock_popen().communicate.return_value = ("ssl_module", "")