예제 #1
0
    def test_gotcha_import(self):
        # standard `replace` caveat, make sure you
        # patch all revelent places where time
        # has been imported:
        
        @replace('time.time',test_time())
        def test_something():
            from time import time
            compare(time(),978307200.0)
            compare(sample1.str_time(),'978307201.0')

        s = should_raise(test_something,AssertionError)
        s()
        # This convoluted check is because we can't stub
        # out time, since we're testing stubbing out time ;-)
        j,t1,j,t2,j = s.raised.args[0].split("'")
        
        # check we can parse the time
        t1 = float(t1)
        # check the t2 bit was as it should be
        compare(t2,'978307201.0')

        # What you need to do is replace the imported type:
        @replace('testfixtures.tests.sample1.time',test_time())
        def test_something():
            compare(sample1.str_time(),'978307200.0')

        test_something()
예제 #2
0
 def test_kw_tzinfo(self):
     with ShouldRaise(TypeError(
         "You don'tfix want to use tzinfo with test_time"
         )):
         @replace('time.time',test_time(year=2001,tzinfo=TestTZInfo()))
         def myfunc():
             pass # pragma: no cover
예제 #3
0
 def test_max_number_tzinfo(self):
     with ShouldRaise(TypeError(
         "You don'tfix want to use tzinfo with test_time"
         )):
         @replace('time.time',test_time(2001,1,2,3,4,5,6,TestTZInfo()))
         def myfunc():
             pass # pragma: no cover
예제 #4
0
    def test_kw_tzinfo(self):
        with ShouldRaise(
                TypeError("You don't want to use tzinfo with test_time")):

            @replace('time.time', test_time(year=2001, tzinfo=TestTZInfo()))
            def myfunc():
                pass
예제 #5
0
    def test_max_number_tzinfo(self):
        with ShouldRaise(
                TypeError("You don't want to use tzinfo with test_time")):

            @replace('time.time',
                     test_time(2001, 1, 2, 3, 4, 5, 6, TestTZInfo()))
            def myfunc():
                pass
 def test_poll(self):
     stream = PiecewiseStream(b'alpha beta gamma omega', max_chunk=5)
     with testfixtures.Replacer() as r:
         mock_time = testfixtures.test_time(delta=0.1, delta_type='seconds')
         r.replace('streamexpect.time.time', mock_time)
         adapter = PollingStreamAdapter(stream)
         for chunk in (b'alpha', b' beta', b' gamm', b'a ome'):
             self.assertEqual(chunk, adapter.poll(1.0))
def test_expect_timeout_if_no_matched_prompt(any_ssh_channel):
    select.select = MagicMock(name='method', return_value=([1], [], []))
    any_ssh_channel.channel.recv.return_value = ANY_DATA_RECEIVED
    with Replacer() as r:
        mock_time = test_time(delta=(ANY_TIMEOUT+1), delta_type='seconds')
        r.replace('steelscript.cmdline.sshchannel.time.time', mock_time)
        with pytest.raises(exceptions.CmdlineTimeout):
            any_ssh_channel.expect(ANY_PROMPT_RE, ANY_TIMEOUT)
def test_expect_if_not_ready_before_timeout(any_ssh_channel):
    select.select = MagicMock(name='method', return_value=([], [], []))
    any_ssh_channel.channel.exit_status_ready.return_value = False
    with Replacer() as r:
        mock_time = test_time(delta=(ANY_TIMEOUT+1), delta_type='seconds')
        r.replace('steelscript.cmdline.sshchannel.time.time', mock_time)
        with pytest.raises(exceptions.CmdlineTimeout):
            any_ssh_channel.expect(ANY_PROMPT_RE, ANY_TIMEOUT)
 def test_timeout(self):
     with testfixtures.Replacer() as r:
         mock_time = testfixtures.test_time(delta=0.1, delta_type='seconds')
         r.replace('streamexpect.time.time', mock_time)
         r.replace('streamexpect.time.sleep', lambda _: None)
         stream = EmptyStream()
         adapter = PollingStreamAdapter(stream)
         with self.assertRaises(ExpectTimeout):
             adapter.poll(1)
    def test_delta(self):
        with OutputCapture() as output:

            time = test_time(delta=0.5, delta_type='seconds')
            print(time())
            print(time())

        output.compare('''
978307200.0
978307200.5
''')
예제 #11
0
    def setUp(self):
        self.log_base_dir = tempfile.mkdtemp()
        self.format = "%Y-%m-%d_%H-%M"

        config_file = "%s/test_logSupport.yaml" %\
            os.path.join(sys.path[0], "test_configurations")
        self.config = yaml.load(file(config_file, 'r'))
        self.replace = Replacer()
        self.replace(
            'glideinwms.lib.logSupport.time.time',
            test_time(2018, 6, 13, 16, 0, 1, delta=60, delta_type='seconds'))
    def test_delta(self):
        with OutputCapture() as output:

            time = test_time(delta=0.5, delta_type='seconds')
            print(time())
            print(time())

        output.compare('''
978307200.0
978307200.5
''')
    def test_specific(self):
        with OutputCapture() as output:

            time = test_time(None)
            time.add(1978, 6, 13, 16, 1)
            time.add(2013, 3, 23, 14, 30)
            print(time())
            print(time())

        output.compare('''
266601660.0
1364049000.0
''')
    def test_simple(self):
        with OutputCapture() as output:

            time = test_time()
            print(time())
            print(time())
            print(time())

        output.compare('''
978307200.0
978307201.0
978307203.0
''')
    def test_specific(self):
        with OutputCapture() as output:

            time = test_time(None)
            time.add(1978, 6, 13, 16, 1)
            time.add(2013, 3, 23, 14, 30)
            print(time())
            print(time())

        output.compare('''
266601660.0
1364049000.0
''')
    def test_simple(self):
        with OutputCapture() as output:

            time = test_time()
            print(time())
            print(time())
            print(time())

        output.compare('''
978307200.0
978307201.0
978307203.0
''')
 def test_timeout(self):
     source, drain = socket.socketpair()
     try:
         with testfixtures.Replacer() as r:
             mock_time = testfixtures.test_time(delta=0.1,
                                                delta_type='seconds')
             r.replace('streamexpect.time.time', mock_time)
             adapter = PollingSocketStreamAdapter(drain)
             with self.assertRaises(ExpectTimeout):
                 adapter.poll(0.01)
     finally:
         source.close()
         drain.close()
 def test_poll(self):
     source, drain = socket.socketpair()
     try:
         with testfixtures.Replacer() as r:
             mock_time = testfixtures.test_time(delta=0.1,
                                                delta_type='seconds')
             r.replace('streamexpect.time.time', mock_time)
             adapter = PollingSocketStreamAdapter(drain)
             for chunk in (b'alpha', b' beta', b' gamm', b'a ome'):
                 source.send(chunk)
                 self.assertEqual(chunk, adapter.poll(1.0))
     finally:
         source.close()
         drain.close()
예제 #19
0
def _setUp(d):
    removeHandlers()
    DummySMTP.install()

    datetime = test_datetime(2007, 1, 1, 10, delta=0)
    time = test_time(2007, 1, 1, 10, delta=0)
    r = Replacer()
    r.replace('mailinglogger.MailingLogger.now', datetime.now)
    r.replace('mailinglogger.common.gethostname', Dummy('host.example.com'))
    r.replace('time.time', time)
    r.replace('os.environ.TZ', 'GMT', strict=False)
    tzset()

    d['r'] = r
    d['smtp'] = DummySMTP
    d['datetime'] = datetime
    d['time'] = time
    d['removeHandlers'] = removeHandlers
예제 #20
0
    def test_query_output_to_file(self):
        with TestingDB("empty.db") as db:
            start_time = datetime(2001, 1, 1)
            with Replace("timewalk.arguments.time", test_time(delta=50, delta_type="seconds")):
                codefiles = ("python.py", "go.go", "swift.swift")
                projects = ("Plugin", None, "Plugin")
                for file, proj in zip(codefiles, projects):
                    argv = [
                        "record",
                        "--file", os.path.join("tests", "samples", "codefiles", file),
                        "--database", db.path,
                        "--config", "tests/samples/configs/empty.ini"
                    ]
                    if proj:
                        argv += ["--project", proj]
                    retval = execute(argv)

                output_file_name = "./test_query_output_to_file.txt"
                argv = [
                    "query",
                    "--database", db.path,
                    "--outfile", output_file_name
                ]

                retval = execute(argv)
                try:
                    with open(output_file_name) as f:
                        actual = json.load(f)
                except json.JSONDecodeError as e:
                    raise e
                expected = [
                    {
                        "start": int(start_time.replace(tzinfo=timezone.utc).timestamp()),
                        "end": int(start_time.replace(tzinfo=timezone.utc).timestamp()) + 50 * (len(codefiles) - 1),
                        "duration": (50 * (len(codefiles) - 1)),
                        "invoker": {},
                        "project": {"Plugin": 50},
                        "language": {"Go": 50, "Swift": 50},
                    },
                ]
                self.assertListEqual(expected, actual)

                if os.path.exists(output_file_name):
                    os.remove(output_file_name)
예제 #21
0
    def test_non_gmt_timezone(self):
        try:
            # setup
            original=environ.get('TZ')
            environ['TZ']='US/Eastern'
            tzset()

            # test
            time = test_time(2001,1,2)
            compare(time(),978393600.0)
            

        finally:
            # restore
            if original is None:
                del environ['TZ']
            else:
                environ['TZ']=original
            tzset()
예제 #22
0
def _setUp(d, stdout=True):
    removeHandlers()
    DummySMTP.install(stdout=stdout)

    atexit_handlers = []
    datetime = test_datetime(2007, 1, 1, 10, delta=0)
    time = test_time(2007, 1, 1, 10, delta=0)
    r = Replacer()
    r.replace('atexit.register', atexit_handlers.append)
    r.replace('mailinglogger.MailingLogger.now', datetime.now)
    r.replace('mailinglogger.common.gethostname', Dummy('host.example.com'))
    r.replace('time.time', time)
    r.replace('os.environ.TZ', 'GMT', strict=False)
    tzset()

    d['atexit_handlers'] = atexit_handlers
    d['r'] = r
    d['smtp'] = DummySMTP
    d['datetime'] = datetime
    d['time'] = time
    d['removeHandlers'] = removeHandlers
예제 #23
0
def _setUp(d, stdout=True):
    removeHandlers()
    DummySMTP.install(stdout=stdout)

    atexit_handlers = []
    datetime = test_datetime(2007, 1, 1, 10, delta=0)
    time = test_time(2007, 1, 1, 10, delta=0)
    r = Replacer()
    r.replace('atexit.register', atexit_handlers.append)
    r.replace('mailinglogger.MailingLogger.now', datetime.now)
    r.replace('mailinglogger.common.gethostname', Dummy('host.example.com'))
    r.replace('time.time', time)
    r.replace('os.environ.TZ', 'GMT', strict=False)
    tzset()

    d['atexit_handlers'] = atexit_handlers
    d['r'] = r
    d['smtp'] = DummySMTP
    d['datetime'] = datetime
    d['time'] = time
    d['removeHandlers'] = removeHandlers
예제 #24
0
    def test_query(self):
        with TestingDB("empty.db") as db, Replace(
                "timewalk.arguments.time", test_time(delta=50, delta_type="seconds")):
            start_time = datetime(2001, 1, 1)
            codefiles = ("python.py", "go.go", "swift.swift")
            for file in codefiles:
                argv = [
                    "record",
                    "--file", os.path.join("tests", "samples", "codefiles", file),
                    "--database", db.path,
                    "--config", "tests/samples/configs/empty.ini"
                ]
                retval = execute(argv)

            argv = [
                "query",
                "--database", db.path,
            ]

            with OutputCapture() as o, LogCapture() as l:
                retval = execute(argv)
                output_text = o.captured
                l.check()
            try:
                actual = json.loads(output_text)
            except json.JSONDecodeError as e:
                print(o.captured)
                raise e
            expected = [
                {
                    "start": int(start_time.replace(tzinfo=timezone.utc).timestamp()),
                    "end": int(start_time.replace(tzinfo=timezone.utc).timestamp()) + 50 * (len(codefiles) - 1),
                    "duration": (50 * (len(codefiles) - 1)),
                    "invoker": {},
                    "project": {},
                    "language": {"Go": 50, "Swift": 50},
                },
            ]
            self.assertListEqual(expected, actual)
예제 #25
0
    def test_report(self):
        with TestingDB("empty.db") as db, Replace(
                "timewalk.arguments.time", test_time(None)) as d:
            codefiles = ("python.py", "go.go", "swift.swift")

            seconds = [0, 20, 50]
            for file, t in zip(codefiles, seconds):
                start_date = datetime(2001, 1, 1, 0, 0, t, 0)
                d.set(start_date)
                argv = [
                    "record",
                    "--file", os.path.join("tests", "samples", "codefiles", file),
                    "--database", db.path,
                    "--project", "My Plugin",
                    "--invoker", '"testAgent/1.0.0-alpha timewalk-testAgent/0.5.0"',
                    "--config", "tests/samples/configs/empty.ini"
                ]
                retval = execute(argv)

            start_date = datetime(2001, 1, 1, 0, 0, 55, 0)
            d.set(start_date)
            argv = [
                "report",
                "--database", db.path,
            ]

            with OutputCapture() as o, LogCapture() as l:
                retval = execute(argv)
                output_text = o.captured

            with open("./tests/samples/output/test_report.txt", "r") as f:
                sevendays = timedelta(days=7)
                expected_start = datetime.fromtimestamp(
                    (start_date - sevendays).replace(tzinfo=timezone.utc).timestamp()).strftime("%b %d, %Y %H:%M:%S")
                expected_end = datetime.fromtimestamp(
                    start_date.replace(tzinfo=timezone.utc).timestamp()).strftime("%b %d, %Y %H:%M:%S")
                expected = f.read().format(expected_start, expected_end)
                self.assertEqual(output_text, expected)
예제 #26
0
파일: shared.py 프로젝트: RyanHartje/vfarm
def setUp(test, self=None, stdout=True):
    if self is None:
        d = test.globs
    else:
        d = self.__dict__

    removeHandlers()
    DummySMTP.install(stdout=stdout)

    datetime = test_datetime(2007, 1, 1, 10, delta=0)
    time = test_time(2007, 1, 1, 10, delta=0)
    r = Replacer()
    r.replace("mailinglogger.MailingLogger.now", datetime.now)
    r.replace("mailinglogger.common.gethostname", Dummy("host.example.com"))
    r.replace("time.time", time)
    r.replace("os.environ.TZ", "GMT", strict=False)
    tzset()

    d["r"] = r
    d["smtp"] = DummySMTP
    d["datetime"] = datetime
    d["time"] = time
    d["removeHandlers"] = removeHandlers
예제 #27
0
def _setUp(test, self=None, stdout=True):
    if self is None:
        d = test.globs
    else:
        d = self.__dict__
        
    removeHandlers()
    DummySMTP.install(stdout=stdout)
    
    datetime = test_datetime(2007, 1, 1, 10, delta=0)
    time = test_time(2007, 1, 1, 10, delta=0)
    r = Replacer()
    r.replace('mailinglogger.MailingLogger.now', datetime.now)
    r.replace('mailinglogger.common.gethostname', Dummy('host.example.com'))
    r.replace('time.time', time)
    r.replace('os.environ.TZ', 'GMT', strict=False)
    tzset()

    d['r'] = r
    d['smtp']=DummySMTP
    d['datetime']=datetime
    d['time']=time
    d['removeHandlers']=removeHandlers
예제 #28
0
def _setUp(test, self=None, stdout=True):
    if self is None:
        d = test.globs
    else:
        d = self.__dict__

    removeHandlers()
    DummySMTP.install(stdout=stdout)

    datetime = test_datetime(2007, 1, 1, 10, delta=0)
    time = test_time(2007, 1, 1, 10, delta=0)
    r = Replacer()
    r.replace('mailinglogger.MailingLogger.now', datetime.now)
    r.replace('mailinglogger.common.gethostname', Dummy('host.example.com'))
    r.replace('time.time', time)
    r.replace('os.environ.TZ', 'GMT', strict=False)
    tzset()

    d['r'] = r
    d['smtp'] = DummySMTP
    d['datetime'] = datetime
    d['time'] = time
    d['removeHandlers'] = removeHandlers
예제 #29
0
 def test_large_report(self):
     with TestingDB("empty.db") as db, Replace(
             "timewalk.arguments.time", test_time(None)) as d:
         codefiles = ("python.py", "go.go", "swift.swift")
예제 #30
0
 def test_tick_when_static(self):
     time = test_time(delta=0)
     compare(time(), expected=978307200.0)
     time.tick(seconds=1)
     compare(time(), expected=978307201.0)
예제 #31
0
 def test_kw_tzinfo(self):
     with ShouldRaise(
             TypeError("You don't want to use tzinfo with test_time")):
         test_time(year=2001, tzinfo=SampleTZInfo())
예제 #32
0
 def test_max_number_tzinfo(self):
     with ShouldRaise(
             TypeError("You don't want to use tzinfo with test_time")):
         test_time(2001, 1, 2, 3, 4, 5, 6, SampleTZInfo())
예제 #33
0
 def test_tick_with_timedelta_instance(self):
     time = test_time(delta=0)
     compare(time(), expected=978307200.0)
     time.tick(timedelta(seconds=1))
     compare(time(), expected=978307201.0)
예제 #34
0
 def test_instance_tzinfo(self):
     from datetime import datetime
     with ShouldRaise(TypeError(
         "You don't want to use tzinfo with test_time"
             )):
         test_time(datetime(2001, 1, 1, tzinfo=SampleTZInfo()))
예제 #35
0
class TestTime(TestCase):
    @replace('time.time', test_time())
    def test_time_call(self):
        from time import time
        compare(time(), 978307200.0)
        compare(time(), 978307201.0)
        compare(time(), 978307203.0)

    @replace('time.time', test_time(2002, 1, 1, 1, 2, 3))
    def test_time_supplied(self):
        from time import time
        compare(time(), 1009846923.0)

    @replace('time.time', test_time(None))
    def test_time_sequence(self, t):
        t.add(2002, 1, 1, 1, 0, 0)
        t.add(2002, 1, 1, 2, 0, 0)
        t.add(2002, 1, 1, 3, 0, 0)
        from time import time
        compare(time(), 1009846800.0)
        compare(time(), 1009850400.0)
        compare(time(), 1009854000.0)

    @replace('time.time', test_time(None))
    def test_add_datetime_supplied(self, t):
        from datetime import datetime
        from time import time
        t.add(datetime(2002, 1, 1, 2))
        compare(time(), 1009850400.0)
        with ShouldRaise(ValueError('Cannot add datetime with tzinfo set')):
            t.add(datetime(2001, 1, 1, tzinfo=TestTZInfo()))

    @replace('time.time', test_time(None))
    def test_now_requested_longer_than_supplied(self, t):
        t.add(2002, 1, 1, 1, 0, 0)
        t.add(2002, 1, 1, 2, 0, 0)
        from time import time
        compare(time(), 1009846800.0)
        compare(time(), 1009850400.0)
        compare(time(), 1009850401.0)
        compare(time(), 1009850403.0)

    @replace('time.time', test_time())
    def test_call(self, t):
        compare(t(), 978307200.0)
        from time import time
        compare(time(), 978307201.0)

    @replace('time.time', test_time())
    def test_repr_time(self):
        from time import time
        compare(repr(time), "<class 'testfixtures.tdatetime.ttime'>")

    @replace('time.time', test_time(delta=10))
    def test_delta(self):
        from time import time
        compare(time(), 978307200.0)
        compare(time(), 978307210.0)
        compare(time(), 978307220.0)

    @replace('time.time', test_time(delta_type='minutes'))
    def test_delta_type(self):
        from time import time
        compare(time(), 978307200.0)
        compare(time(), 978307260.0)
        compare(time(), 978307380.0)

    @replace('time.time', test_time(None))
    def test_set(self):
        from time import time
        time.set(2001, 1, 1, 1, 0, 1)
        compare(time(), 978310801.0)
        time.set(2002, 1, 1, 1, 0, 0)
        compare(time(), 1009846800.0)
        compare(time(), 1009846802.0)

    @replace('time.time', test_time(None))
    def test_set_datetime_supplied(self, t):
        from datetime import datetime
        from time import time
        t.set(datetime(2001, 1, 1, 1, 0, 1))
        compare(time(), 978310801.0)
        with ShouldRaise(ValueError('Cannot set datetime with tzinfo set')):
            t.set(datetime(2001, 1, 1, tzinfo=TestTZInfo()))

    @replace('time.time', test_time(None))
    def test_set_kw(self):
        from time import time
        time.set(year=2001, month=1, day=1, hour=1, second=1)
        compare(time(), 978310801.0)

    @replace('time.time', test_time(None))
    def test_set_kw_tzinfo(self):
        from time import time
        with ShouldRaise(TypeError('Cannot set tzinfo on ttime')):
            time.set(year=2001, tzinfo=TestTZInfo())

    @replace('time.time', test_time(None))
    def test_set_args_tzinfo(self):
        from time import time
        with ShouldRaise(TypeError('Cannot set tzinfo on ttime')):
            time.set(2002, 1, 2, 3, 4, 5, 6, TestTZInfo())

    @replace('time.time', test_time(None))
    def test_add_kw(self):
        from time import time
        time.add(year=2001, month=1, day=1, hour=1, second=1)
        compare(time(), 978310801.0)

    @replace('time.time', test_time(None))
    def test_add_tzinfo_kw(self):
        from time import time
        with ShouldRaise(TypeError('Cannot add tzinfo to ttime')):
            time.add(year=2001, tzinfo=TestTZInfo())

    @replace('time.time', test_time(None))
    def test_add_tzinfo_args(self):
        from time import time
        with ShouldRaise(TypeError('Cannot add tzinfo to ttime')):
            time.add(2001, 1, 2, 3, 4, 5, 6, TestTZInfo())

    @replace('time.time', test_time(2001, 1, 2, 3, 4, 5, 600000))
    def test_max_number_args(self):
        from time import time
        compare(time(), 978404645.6)

    def test_max_number_tzinfo(self):
        with ShouldRaise(
                TypeError("You don't want to use tzinfo with test_time")):

            @replace('time.time',
                     test_time(2001, 1, 2, 3, 4, 5, 6, TestTZInfo()))
            def myfunc():
                pass

    @replace('time.time', test_time(2001, 1, 2))
    def test_min_number_args(self):
        from time import time
        compare(time(), 978393600.0)

    @replace('time.time',
             test_time(year=2001,
                       month=1,
                       day=2,
                       hour=3,
                       minute=4,
                       second=5,
                       microsecond=6))
    def test_all_kw(self):
        from time import time
        compare(time(), 978404645.000006)

    def test_kw_tzinfo(self):
        with ShouldRaise(
                TypeError("You don't want to use tzinfo with test_time")):

            @replace('time.time', test_time(year=2001, tzinfo=TestTZInfo()))
            def myfunc():
                pass

    def test_subsecond_deltas(self):
        time = test_time(delta=0.5)
        compare(time(), 978307200.0)
        compare(time(), 978307200.5)
        compare(time(), 978307201.0)

    def test_ms_deltas(self):
        time = test_time(delta=1000, delta_type='microseconds')
        compare(time(), 978307200.0)
        compare(time(), 978307200.001)
        compare(time(), 978307200.002)
예제 #36
0
 def test_instantiate_with_datetime(self):
     from datetime import datetime
     t = test_time(datetime(2002, 1, 1, 2))
     compare(t(), 1009850400.0)
예제 #37
0
 def test_ms_deltas(self):
     time = test_time(delta=1000, delta_type='microseconds')
     compare(time(), 978307200.0)
     compare(time(), 978307200.001)
     compare(time(), 978307200.002)
예제 #38
0
 def test_subsecond_deltas(self):
     time = test_time(delta=0.5)
     compare(time(), 978307200.0)
     compare(time(), 978307200.5)
     compare(time(), 978307201.0)
예제 #39
0
class TestTime(TestCase):

    @replace('time.time', test_time())
    def test_time_call(self):
        from time import time
        compare(time(), 978307200.0)
        compare(time(), 978307201.0)
        compare(time(), 978307203.0)

    @replace('time.time', test_time(2002, 1, 1, 1, 2, 3))
    def test_time_supplied(self):
        from time import time
        compare(time(), 1009846923.0)

    @replace('time.time', test_time(None))
    def test_time_sequence(self, t):
        t.add(2002, 1, 1, 1, 0, 0)
        t.add(2002, 1, 1, 2, 0, 0)
        t.add(2002, 1, 1, 3, 0, 0)
        from time import time
        compare(time(), 1009846800.0)
        compare(time(), 1009850400.0)
        compare(time(), 1009854000.0)

    @replace('time.time', test_time(None))
    def test_add_datetime_supplied(self, t):
        from datetime import datetime
        from time import time
        t.add(datetime(2002, 1, 1, 2))
        compare(time(), 1009850400.0)
        tzinfo = SampleTZInfo()
        tzrepr = repr(tzinfo)
        with ShouldRaise(ValueError(
            'Cannot add datetime with tzinfo of %s as configured to use None' %(
                tzrepr
            ))):
            t.add(datetime(2001, 1, 1, tzinfo=tzinfo))

    def test_instantiate_with_datetime(self):
        from datetime import datetime
        t = test_time(datetime(2002, 1, 1, 2))
        compare(t(), 1009850400.0)

    @replace('time.time', test_time(None))
    def test_now_requested_longer_than_supplied(self, t):
        t.add(2002, 1, 1, 1, 0, 0)
        t.add(2002, 1, 1, 2, 0, 0)
        from time import time
        compare(time(), 1009846800.0)
        compare(time(), 1009850400.0)
        compare(time(), 1009850401.0)
        compare(time(), 1009850403.0)

    @replace('time.time', test_time())
    def test_call(self, t):
        compare(t(), 978307200.0)
        from time import time
        compare(time(), 978307201.0)

    @replace('time.time', test_time())
    def test_repr_time(self):
        from time import time
        compare(repr(time), "<class 'testfixtures.tdatetime.ttime'>")

    @replace('time.time', test_time(delta=10))
    def test_delta(self):
        from time import time
        compare(time(), 978307200.0)
        compare(time(), 978307210.0)
        compare(time(), 978307220.0)

    @replace('time.time', test_time(delta_type='minutes'))
    def test_delta_type(self):
        from time import time
        compare(time(), 978307200.0)
        compare(time(), 978307260.0)
        compare(time(), 978307380.0)

    @replace('time.time', test_time(None))
    def test_set(self):
        from time import time
        time.set(2001, 1, 1, 1, 0, 1)
        compare(time(), 978310801.0)
        time.set(2002, 1, 1, 1, 0, 0)
        compare(time(), 1009846800.0)
        compare(time(), 1009846802.0)

    @replace('time.time', test_time(None))
    def test_set_datetime_supplied(self, t):
        from datetime import datetime
        from time import time
        t.set(datetime(2001, 1, 1, 1, 0, 1))
        compare(time(), 978310801.0)
        tzinfo = SampleTZInfo()
        tzrepr = repr(tzinfo)
        with ShouldRaise(ValueError(
            'Cannot add datetime with tzinfo of %s as configured to use None' %(
                tzrepr
            ))):
            t.set(datetime(2001, 1, 1, tzinfo=tzinfo))

    @replace('time.time', test_time(None))
    def test_set_kw(self):
        from time import time
        time.set(year=2001, month=1, day=1, hour=1, second=1)
        compare(time(), 978310801.0)

    @replace('time.time', test_time(None))
    def test_set_kw_tzinfo(self):
        from time import time
        with ShouldRaise(TypeError('Cannot add using tzinfo on ttime')):
            time.set(year=2001, tzinfo=SampleTZInfo())

    @replace('time.time', test_time(None))
    def test_set_args_tzinfo(self):
        from time import time
        with ShouldRaise(TypeError('Cannot add using tzinfo on ttime')):
            time.set(2002, 1, 2, 3, 4, 5, 6, SampleTZInfo())

    @replace('time.time', test_time(None))
    def test_add_kw(self):
        from time import time
        time.add(year=2001, month=1, day=1, hour=1, second=1)
        compare(time(), 978310801.0)

    @replace('time.time', test_time(None))
    def test_add_tzinfo_kw(self):
        from time import time
        with ShouldRaise(TypeError('Cannot add using tzinfo on ttime')):
            time.add(year=2001, tzinfo=SampleTZInfo())

    @replace('time.time', test_time(None))
    def test_add_tzinfo_args(self):
        from time import time
        with ShouldRaise(TypeError('Cannot add using tzinfo on ttime')):
            time.add(2001, 1, 2, 3, 4, 5, 6, SampleTZInfo())

    @replace('time.time', test_time(2001, 1, 2, 3, 4, 5, 600000))
    def test_max_number_args(self):
        from time import time
        compare(time(), 978404645.6)

    def test_max_number_tzinfo(self):
        with ShouldRaise(TypeError(
            "You don't want to use tzinfo with test_time"
                )):
            @replace('time.time',
                     test_time(2001, 1, 2, 3, 4, 5, 6, SampleTZInfo()))
            def myfunc():
                pass  # pragma: no cover

    @replace('time.time', test_time(2001, 1, 2))
    def test_min_number_args(self):
        from time import time
        compare(time(), 978393600.0)

    @replace('time.time', test_time(
        year=2001,
        month=1,
        day=2,
        hour=3,
        minute=4,
        second=5,
        microsecond=6,
        ))
    def test_all_kw(self):
        from time import time
        compare(time(), 978404645.000006)

    def test_kw_tzinfo(self):
        with ShouldRaise(TypeError(
            "You don't want to use tzinfo with test_time"
                )):
            @replace('time.time', test_time(year=2001, tzinfo=SampleTZInfo()))
            def myfunc():
                pass  # pragma: no cover

    def test_instance_tzinfo(self):
        from datetime import datetime
        with ShouldRaise(TypeError(
            "You don't want to use tzinfo with test_time"
                )):
            test_time(datetime(2001, 1, 1, tzinfo=SampleTZInfo()))

    def test_subsecond_deltas(self):
        time = test_time(delta=0.5)
        compare(time(), 978307200.0)
        compare(time(), 978307200.5)
        compare(time(), 978307201.0)

    def test_ms_deltas(self):
        time = test_time(delta=1000, delta_type='microseconds')
        compare(time(), 978307200.0)
        compare(time(), 978307200.001)
        compare(time(), 978307200.002)

    def test_tick_when_static(self):
        time = test_time(delta=0)
        compare(time(), expected=978307200.0)
        time.tick(seconds=1)
        compare(time(), expected=978307201.0)

    def test_tick_when_dynamic(self):
        # hopefully not that common?
        time = test_time()
        compare(time(), expected=978307200.0)
        time.tick(seconds=1)
        compare(time(), expected=978307202.0)

    def test_tick_with_timedelta_instance(self):
        time = test_time(delta=0)
        compare(time(), expected=978307200.0)
        time.tick(timedelta(seconds=1))
        compare(time(), expected=978307201.0)
예제 #40
0
 def test_subsecond_deltas(self):
     time = test_time(delta=0.5)
     compare(time(), 978307200.0)
     compare(time(), 978307200.5)
     compare(time(), 978307201.0)
예제 #41
0
 def test_ms_deltas(self):
     time = test_time(delta=1000, delta_type='microseconds')
     compare(time(), 978307200.0)
     compare(time(), 978307200.001)
     compare(time(), 978307200.002)
예제 #42
0
 def test_tick_when_dynamic(self):
     # hopefully not that common?
     time = test_time()
     compare(time(), expected=978307200.0)
     time.tick(seconds=1)
     compare(time(), expected=978307202.0)
예제 #43
0
    if time.localtime(t).tm_isdst and time.daylight:
        return -time.altzone/3600, time.tzname[1]
    else:
        return -time.timezone/3600, time.tzname[0]

if __name__ == "__main__":
    import logging

    # testfixtures needs to be installed separately,
    # but it is only used for testing the handler.
    from testfixtures import test_time

    #pathfmt = "%Y/%m-%b/%Y-%m-%d.log"
    pathfmt = "%Y/%Y-%m-%b_Week-%W.log"
    my_time = test_time(*time.localtime()[0:5], delta=1, delta_type="hours")

    handler = TestDatedDailyRotationHandler(pathformat=pathfmt, timefunc=my_time, utc=True)#DailyRotationHandler(utc=True)#
    print(handler._format_time())

    logger = logging.getLogger("main")

    handler.set_logging_info_func(logger.info)

    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)


    logger.info("Testing, testing, please work!")

    for i in range(300):