File: test_utils_trackref.py

package info (click to toggle)
python-scrapy 2.4.1-2%2Bdeb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 4,748 kB
  • sloc: python: 32,888; xml: 199; makefile: 90; sh: 7
file content (85 lines) | stat: -rw-r--r-- 2,098 bytes parent folder | download
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
import unittest
from io import StringIO
from time import sleep, time
from unittest import mock

from twisted.trial.unittest import SkipTest

from scrapy.utils import trackref


class Foo(trackref.object_ref):
    pass


class Bar(trackref.object_ref):
    pass


class TrackrefTestCase(unittest.TestCase):

    def setUp(self):
        trackref.live_refs.clear()

    def test_format_live_refs(self):
        o1 = Foo()  # NOQA
        o2 = Bar()  # NOQA
        o3 = Foo()  # NOQA
        self.assertEqual(
            trackref.format_live_refs(),
            '''\
Live References

Bar                                 1   oldest: 0s ago
Foo                                 2   oldest: 0s ago
''')

        self.assertEqual(
            trackref.format_live_refs(ignore=Foo),
            '''\
Live References

Bar                                 1   oldest: 0s ago
''')

    @mock.patch('sys.stdout', new_callable=StringIO)
    def test_print_live_refs_empty(self, stdout):
        trackref.print_live_refs()
        self.assertEqual(stdout.getvalue(), 'Live References\n\n\n')

    @mock.patch('sys.stdout', new_callable=StringIO)
    def test_print_live_refs_with_objects(self, stdout):
        o1 = Foo()  # NOQA
        trackref.print_live_refs()
        self.assertEqual(stdout.getvalue(), '''\
Live References

Foo                                 1   oldest: 0s ago\n\n''')

    def test_get_oldest(self):
        o1 = Foo()  # NOQA

        o1_time = time()

        o2 = Bar()  # NOQA

        o3_time = time()
        if o3_time <= o1_time:
            sleep(0.01)
            o3_time = time()
        if o3_time <= o1_time:
            raise SkipTest('time.time is not precise enough')

        o3 = Foo()  # NOQA
        self.assertIs(trackref.get_oldest('Foo'), o1)
        self.assertIs(trackref.get_oldest('Bar'), o2)
        self.assertIsNone(trackref.get_oldest('XXX'))

    def test_iter_all(self):
        o1 = Foo()  # NOQA
        o2 = Bar()  # NOQA
        o3 = Foo()  # NOQA
        self.assertEqual(
            set(trackref.iter_all('Foo')),
            {o1, o3},
        )