summaryrefslogtreecommitdiffstats
path: root/Lib/test/test_xreload.py
blob: dcd6569fd27e113d728ec9d6761e9ffe7281ea71 (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
"""Doctests for module reloading.

>>> from xreload import xreload
>>> from test.test_xreload import make_mod
>>> make_mod()
>>> import x
>>> C = x.C
>>> Cfoo = C.foo
>>> Cbar = C.bar
>>> Cstomp = C.stomp
>>> b = C()
>>> bfoo = b.foo
>>> b.foo()
42
>>> bfoo()
42
>>> Cfoo(b)
42
>>> Cbar()
42 42
>>> Cstomp()
42 42 42
>>> make_mod(repl="42", subst="24")
>>> xreload(x)
<module 'x' (built-in)>
>>> b.foo()
24
>>> bfoo()
24
>>> Cfoo(b)
24
>>> Cbar()
24 24
>>> Cstomp()
24 24 24

"""

SAMPLE_CODE = """
class C:
    def foo(self):
        print(42)
    @classmethod
    def bar(cls):
        print(42, 42)
    @staticmethod
    def stomp():
        print (42, 42, 42)
"""

import os
import sys
import shutil
import doctest
import xreload
import tempfile
from test.test_support import run_unittest

tempdir = None
save_path = None


def setUp(unused=None):
    global tempdir, save_path
    tempdir = tempfile.mkdtemp()
    save_path = list(sys.path)
    sys.path.append(tempdir)


def tearDown(unused=None):
    global tempdir, save_path
    if save_path is not None:
        sys.path = save_path
        save_path = None
    if tempdir is not None:
        shutil.rmtree(tempdir)
        tempdir = None
        

def make_mod(name="x", repl=None, subst=None):
    if not tempdir:
        setUp()
        assert tempdir
    fn = os.path.join(tempdir, name + ".py")
    f = open(fn, "w")
    sample = SAMPLE_CODE
    if repl is not None and subst is not None:
        sample = sample.replace(repl, subst)
    try:
        f.write(sample)
    finally:
        f.close()


def test_suite():
    return doctest.DocTestSuite(setUp=setUp, tearDown=tearDown)


def test_main():
    run_unittest(test_suite())

if __name__ == "__main__":
    test_main()