aboutsummaryrefslogtreecommitdiffstats
path: root/test/mitmproxy/addons/test_script.py
blob: a41f6103536b1cafc94f1087d77c57cfb94fcc2f (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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import traceback
import sys
import time
import re

from mitmproxy.test import tflow
from mitmproxy.test import tutils
from mitmproxy.test import taddons
from mitmproxy import exceptions
from mitmproxy import options
from mitmproxy import proxy
from mitmproxy import master

from mitmproxy.addons import script

import watchdog.events

from .. import tutils as ttutils


def test_ns():
    n = script.NS({})
    n.one = "one"
    assert n.one == "one"
    assert n.__dict__["ns"]["one"] == "one"


def test_scriptenv():
    with taddons.context() as tctx:
        with script.scriptenv("path", []):
            raise SystemExit
        assert tctx.master.event_log[0][0] == "error"
        assert "exited" in tctx.master.event_log[0][1]

        tctx.master.clear()
        with script.scriptenv("path", []):
            raise ValueError("fooo")
        assert tctx.master.event_log[0][0] == "error"
        assert "foo" in tctx.master.event_log[0][1]


class Called:
    def __init__(self):
        self.called = False

    def __call__(self, *args, **kwargs):
        self.called = True


def test_reloadhandler():
    rh = script.ReloadHandler(Called())
    assert not rh.filter(watchdog.events.DirCreatedEvent("path"))
    assert not rh.filter(watchdog.events.FileModifiedEvent("/foo/.bar"))
    assert rh.filter(watchdog.events.FileModifiedEvent("/foo/bar"))

    assert not rh.callback.called
    rh.on_modified(watchdog.events.FileModifiedEvent("/foo/bar"))
    assert rh.callback.called
    rh.callback.called = False

    rh.on_created(watchdog.events.FileCreatedEvent("foo"))
    assert rh.callback.called


class TestParseCommand:
    def test_empty_command(self):
        with tutils.raises(exceptions.AddonError):
            script.parse_command("")

        with tutils.raises(exceptions.AddonError):
            script.parse_command("  ")

    def test_no_script_file(self):
        with tutils.raises("not found"):
            script.parse_command("notfound")

        with tutils.tmpdir() as dir:
            with tutils.raises("not a file"):
                script.parse_command(dir)

    def test_parse_args(self):
        with tutils.chdir(tutils.test_data.dirname):
            assert script.parse_command(
                "mitmproxy/data/addonscripts/recorder.py"
            ) == ("mitmproxy/data/addonscripts/recorder.py", [])
            assert script.parse_command(
                "mitmproxy/data/addonscripts/recorder.py foo bar"
            ) == ("mitmproxy/data/addonscripts/recorder.py", ["foo", "bar"])
            assert script.parse_command(
                "mitmproxy/data/addonscripts/recorder.py 'foo bar'"
            ) == ("mitmproxy/data/addonscripts/recorder.py", ["foo bar"])

    @ttutils.skip_not_windows
    def test_parse_windows(self):
        with tutils.chdir(tutils.test_data.dirname):
            assert script.parse_command(
                "mitmproxy/data\\addonscripts\\recorder.py"
            ) == ("mitmproxy/data\\addonscripts\\recorder.py", [])
            assert script.parse_command(
                "mitmproxy/data\\addonscripts\\recorder.py 'foo \\ bar'"
            ) == ("mitmproxy/data\\addonscripts\\recorder.py", ['foo \\ bar'])


def test_load_script():
    ns = script.load_script(
        tutils.test_data.path(
            "mitmproxy/data/addonscripts/recorder.py"
        ), []
    )
    assert ns.start


class TestScript:
    def test_simple(self):
        with taddons.context():
            sc = script.Script(
                tutils.test_data.path(
                    "mitmproxy/data/addonscripts/recorder.py"
                )
            )
            sc.load_script()
            assert sc.ns.call_log == [
                ("solo", "start", (), {}),
            ]

            sc.ns.call_log = []
            f = tflow.tflow(resp=True)
            sc.request(f)

            recf = sc.ns.call_log[0]
            assert recf[1] == "request"

    def test_reload(self):
        with taddons.context() as tctx:
            with tutils.tmpdir():
                with open("foo.py", "w"):
                    pass
                sc = script.Script("foo.py")
                tctx.configure(sc)
                for _ in range(100):
                    with open("foo.py", "a") as f:
                        f.write(".")
                    sc.tick()
                    time.sleep(0.1)
                    if tctx.master.event_log:
                        return
                raise AssertionError("Change event not detected.")

    def test_exception(self):
        with taddons.context() as tctx:
            sc = script.Script(
                tutils.test_data.path("mitmproxy/data/addonscripts/error.py")
            )
            sc.start()
            f = tflow.tflow(resp=True)
            sc.request(f)
            assert tctx.master.event_log[0][0] == "error"
            assert len(tctx.master.event_log[0][1].splitlines()) == 6
            assert re.search(r'addonscripts[\\/]error.py", line \d+, in request', tctx.master.event_log[0][1])
            assert re.search(r'addonscripts[\\/]error.py", line \d+, in mkerr', tctx.master.event_log[0][1])
            assert tctx.master.event_log[0][1].endswith("ValueError: Error!\n")

    def test_addon(self):
        with taddons.context() as tctx:
            sc = script.Script(
                tutils.test_data.path(
                    "mitmproxy/data/addonscripts/addon.py"
                )
            )
            sc.start()
            tctx.configure(sc)
            assert sc.ns.event_log == [
                'scriptstart', 'addonstart', 'addonconfigure'
            ]


class TestCutTraceback:
    def raise_(self, i):
        if i > 0:
            self.raise_(i - 1)
        raise RuntimeError()

    def test_simple(self):
        try:
            self.raise_(4)
        except RuntimeError:
            tb = sys.exc_info()[2]
            tb_cut = script.cut_traceback(tb, "test_simple")
            assert len(traceback.extract_tb(tb_cut)) == 5

            tb_cut2 = script.cut_traceback(tb, "nonexistent")
            assert len(traceback.extract_tb(tb_cut2)) == len(traceback.extract_tb(tb))


class TestScriptLoader:
    def test_run_once(self):
        o = options.Options(scripts=[])
        m = master.Master(o, proxy.DummyServer())
        sl = script.ScriptLoader()
        m.addons.add(sl)

        f = tflow.tflow(resp=True)
        with m.handlecontext():
            sc = sl.run_once(
                tutils.test_data.path(
                    "mitmproxy/data/addonscripts/recorder.py"
                ), [f]
            )
        evts = [i[1] for i in sc.ns.call_log]
        assert evts == ['start', 'requestheaders', 'request', 'responseheaders', 'response', 'done']

        with m.handlecontext():
            tutils.raises(
                "file not found",
                sl.run_once,
                "nonexistent",
                [f]
            )

    def test_simple(self):
        o = options.Options(scripts=[])
        m = master.Master(o, proxy.DummyServer())
        sc = script.ScriptLoader()
        m.addons.add(sc)
        assert len(m.addons) == 1
        o.update(
            scripts = [
                tutils.test_data.path("mitmproxy/data/addonscripts/recorder.py")
            ]
        )
        assert len(m.addons) == 2
        o.update(scripts = [])
        assert len(m.addons) == 1

    def test_dupes(self):
        o = options.Options(scripts=["one", "one"])
        m = master.Master(o, proxy.DummyServer())
        sc = script.ScriptLoader()
        tutils.raises(exceptions.OptionsError, m.addons.add, o, sc)

    def test_order(self):
        rec = tutils.test_data.path("mitmproxy/data/addonscripts/recorder.py")
        sc = script.ScriptLoader()
        with taddons.context() as tctx:
            tctx.master.addons.add(sc)
            tctx.configure(
                sc,
                scripts = [
                    "%s %s" % (rec, "a"),
                    "%s %s" % (rec, "b"),
                    "%s %s" % (rec, "c"),
                ]
            )
            debug = [(i[0], i[1]) for i in tctx.master.event_log if i[0] == "debug"]
            assert debug == [
                ('debug', 'a start'), ('debug', 'a configure'),
                ('debug', 'b start'), ('debug', 'b configure'),
                ('debug', 'c start'), ('debug', 'c configure')
            ]
            tctx.master.event_log = []
            tctx.configure(
                sc,
                scripts = [
                    "%s %s" % (rec, "c"),
                    "%s %s" % (rec, "a"),
                    "%s %s" % (rec, "b"),
                ]
            )
            debug = [(i[0], i[1]) for i in tctx.master.event_log if i[0] == "debug"]
            # No events, only order has changed
            assert debug == []

            tctx.master.event_log = []
            tctx.configure(
                sc,
                scripts = [
                    "%s %s" % (rec, "x"),
                    "%s %s" % (rec, "a"),
                ]
            )
            debug = [(i[0], i[1]) for i in tctx.master.event_log if i[0] == "debug"]
            assert debug == [
                ('debug', 'c done'),
                ('debug', 'b done'),
                ('debug', 'x start'),
                ('debug', 'x configure'),
            ]