Welcome to mirror list, hosted at ThFree Co, Russian Federation.

apache_test.py « letshelp_certbot « letshelp-certbot - github.com/certbot/certbot.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0853046b4160e9dd218c8e277d326c2022351000 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""Tests for letshelp.letshelp_certbot_apache.py"""
import argparse
import functools
import os
import subprocess
import tarfile
import tempfile
import unittest

# six is used in mock.patch()
import mock
import pkg_resources
import six  # pylint: disable=unused-import

import letshelp_certbot.apache as letshelp_le_apache

_PARTIAL_CONF_PATH = os.path.join("mods-available", "ssl.load")
_PARTIAL_LINK_PATH = os.path.join("mods-enabled", "ssl.load")
_CONFIG_FILE = pkg_resources.resource_filename(
    __name__, os.path.join("testdata", _PARTIAL_CONF_PATH))
_PASSWD_FILE = pkg_resources.resource_filename(
    __name__, os.path.join("testdata", "uncommonly_named_p4sswd"))
_KEY_FILE = pkg_resources.resource_filename(
    __name__, os.path.join("testdata", "uncommonly_named_k3y"))
_SECRET_FILE = pkg_resources.resource_filename(
    __name__, os.path.join("testdata", "super_secret_file.txt"))


_MODULE_NAME = "letshelp_certbot.apache"


_COMPILE_SETTINGS = """Server version: Apache/2.4.10 (Debian)
Server built:   Mar 15 2015 09:51:43
Server's Module Magic Number: 20120211:37
Server loaded:  APR 1.5.1, APR-UTIL 1.5.4
Compiled using: APR 1.5.1, APR-UTIL 1.5.4
Architecture:   64-bit
Server MPM:     event
  threaded:     yes (fixed thread count)
    forked:     yes (variable process count)
Server compiled with....
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=256
 -D HTTPD_ROOT="/etc/apache2"
 -D SUEXEC_BIN="/usr/lib/apache2/suexec"
 -D DEFAULT_PIDLOG="/var/run/apache2.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="mime.types"
 -D SERVER_CONFIG_FILE="apache2.conf"

"""


class LetsHelpApacheTest(unittest.TestCase):
    @mock.patch(_MODULE_NAME + ".copy_config")
    def test_make_and_verify_selection(self, mock_copy_config):
        mock_copy_config.return_value = (["apache2.conf"], ["apache2"])

        with mock.patch("six.moves.input") as mock_input:
            with mock.patch(_MODULE_NAME + ".sys.stdout"):
                mock_input.side_effect = ["Yes", "No"]
                letshelp_le_apache.make_and_verify_selection("root", "temp")
                self.assertRaises(
                    SystemExit, letshelp_le_apache.make_and_verify_selection,
                    "server_root", "temp_dir")

    def test_copy_config(self):
        tempdir = tempfile.mkdtemp()
        server_root = pkg_resources.resource_filename(__name__, "testdata")
        letshelp_le_apache.copy_config(server_root, tempdir)

        temp_testdata = os.path.join(tempdir, "testdata")
        self.assertFalse(os.path.exists(os.path.join(
            temp_testdata, os.path.basename(_PASSWD_FILE))))
        self.assertFalse(os.path.exists(os.path.join(
            temp_testdata, os.path.basename(_KEY_FILE))))
        self.assertFalse(os.path.exists(os.path.join(
            temp_testdata, os.path.basename(_SECRET_FILE))))
        self.assertTrue(os.path.exists(os.path.join(
            temp_testdata, _PARTIAL_CONF_PATH)))
        self.assertTrue(os.path.exists(os.path.join(
            temp_testdata, _PARTIAL_LINK_PATH)))

    def test_copy_file_without_comments(self):
        dest = tempfile.mkstemp()[1]
        letshelp_le_apache.copy_file_without_comments(_PASSWD_FILE, dest)

        with open(_PASSWD_FILE) as original:
            with open(dest) as copy:
                for original_line, copied_line in zip(original, copy):
                    self.assertEqual(original_line, copied_line)

    @mock.patch(_MODULE_NAME + ".subprocess.Popen")
    def test_safe_config_file(self, mock_popen):
        mock_popen().communicate.return_value = ("PEM RSA private key", None)
        self.assertFalse(letshelp_le_apache.safe_config_file("filename"))

        mock_popen().communicate.return_value = ("ASCII text", None)
        self.assertFalse(letshelp_le_apache.safe_config_file(_PASSWD_FILE))
        self.assertFalse(letshelp_le_apache.safe_config_file(_KEY_FILE))
        self.assertFalse(letshelp_le_apache.safe_config_file(_SECRET_FILE))
        self.assertTrue(letshelp_le_apache.safe_config_file(_CONFIG_FILE))

    @mock.patch(_MODULE_NAME + ".subprocess.Popen")
    def test_tempdir(self, mock_popen):
        mock_popen().communicate.side_effect = [
            ("version", None), ("modules", None), ("vhosts", None)]
        args = _get_args()

        tempdir = letshelp_le_apache.setup_tempdir(args)

        with open(os.path.join(tempdir, "config_file")) as config_fd:
            self.assertEqual(config_fd.read(), args.config_file + "\n")

        with open(os.path.join(tempdir, "version")) as version_fd:
            self.assertEqual(version_fd.read(), "version")

        with open(os.path.join(tempdir, "modules")) as modules_fd:
            self.assertEqual(modules_fd.read(), "modules")

        with open(os.path.join(tempdir, "vhosts")) as vhosts_fd:
            self.assertEqual(vhosts_fd.read(), "vhosts")

    @mock.patch(_MODULE_NAME + ".subprocess.check_call")
    def test_verify_config(self, mock_check_call):
        args = _get_args()
        mock_check_call.side_effect = [
            None, OSError, subprocess.CalledProcessError(1, "apachectl")]

        letshelp_le_apache.verify_config(args)
        self.assertRaises(SystemExit, letshelp_le_apache.verify_config, args)
        self.assertRaises(SystemExit, letshelp_le_apache.verify_config, args)

    @mock.patch(_MODULE_NAME + ".subprocess.Popen")
    def test_locate_config(self, mock_popen):
        mock_popen().communicate.side_effect = [
            OSError, ("bad_output", None), (_COMPILE_SETTINGS, None)]

        self.assertRaises(
            SystemExit, letshelp_le_apache.locate_config, "ctl")
        self.assertRaises(
            SystemExit, letshelp_le_apache.locate_config, "ctl")
        server_root, config_file = letshelp_le_apache.locate_config("ctl")
        self.assertEqual(server_root, "/etc/apache2")
        self.assertEqual(config_file, "apache2.conf")

    @mock.patch(_MODULE_NAME + ".argparse")
    def test_get_args(self, mock_argparse):
        argv = ["-d", "/etc/apache2"]
        mock_argparse.ArgumentParser.return_value = _create_mock_parser(argv)
        self.assertRaises(SystemExit, letshelp_le_apache.get_args)

        server_root = "/etc/apache2"
        config_file = server_root + "/apache2.conf"
        argv = ["-d", server_root, "-f", config_file]
        mock_argparse.ArgumentParser.return_value = _create_mock_parser(argv)
        args = letshelp_le_apache.get_args()
        self.assertEqual(args.apache_ctl, "apachectl")
        self.assertEqual(args.server_root, server_root)
        self.assertEqual(args.config_file, os.path.basename(config_file))

        server_root = "/etc/apache2"
        config_file = "/etc/httpd/httpd.conf"
        argv = ["-d", server_root, "-f", config_file]
        mock_argparse.ArgumentParser.return_value = _create_mock_parser(argv)
        self.assertRaises(SystemExit, letshelp_le_apache.get_args)

    def test_main_with_args(self):
        with mock.patch(_MODULE_NAME + ".get_args"):
            self._test_main_common()

    def test_main_without_args(self):
        with mock.patch(_MODULE_NAME + ".get_args") as get_args:
            args = _get_args()
            server_root, config_file = args.server_root, args.config_file
            args.server_root = args.config_file = None
            get_args.return_value = args
            with mock.patch(_MODULE_NAME + ".locate_config") as locate:
                locate.return_value = (server_root, config_file)
                self._test_main_common()

    def _test_main_common(self):
        with mock.patch(_MODULE_NAME + ".verify_config"):
            with mock.patch(_MODULE_NAME + ".setup_tempdir") as mock_setup:
                tempdir_path = tempfile.mkdtemp()
                mock_setup.return_value = tempdir_path
                with mock.patch(_MODULE_NAME + ".make_and_verify_selection"):
                    testdir_basename = "test"
                    os.mkdir(os.path.join(tempdir_path, testdir_basename))

                    letshelp_le_apache.main()

                    tar = tarfile.open(os.path.join(
                        tempdir_path, "config.tar.gz"))

                    tempdir = tar.next()
                    if tempdir is None:
                        self.fail("Invalid tarball!")  # pragma: no cover
                    else:
                        self.assertTrue(tempdir.isdir())
                        self.assertEqual(tempdir.name, ".")

                    testdir = tar.next()
                    if testdir is None:
                        self.fail("Invalid tarball!")  # pragma: no cover
                    else:
                        self.assertTrue(testdir.isdir())
                        self.assertEqual(os.path.basename(testdir.name),
                                         testdir_basename)

                    self.assertEqual(tar.next(), None)


def _create_mock_parser(argv):
    parser = argparse.ArgumentParser()
    mock_parser = mock.MagicMock()
    mock_parser.add_argument = parser.add_argument
    mock_parser.parse_args = functools.partial(parser.parse_args, argv)

    return mock_parser


def _get_args():
    args = argparse.Namespace()
    args.apache_ctl = "apache_ctl"
    args.config_file = "config_file"
    args.server_root = "server_root"

    return args


if __name__ == "__main__":
    unittest.main()  # pragma: no cover