How to use fake_clock method in freezegun

Best Python code snippet using freezegun

test_termui.py

Source: test_termui.py Github

copy

Full Screen

1import click2import time3class FakeClock(object):4 def __init__(self):5 self.now = time.time()6 def advance_time(self, seconds=1):7 self.now += seconds8 def time(self):9 return self.now10def test_progressbar_strip_regression(runner, monkeypatch):11 fake_clock = FakeClock()12 label = ' padded line'13 @click.command()14 def cli():15 with click.progressbar(tuple(range(10)), label=label) as progress:16 for thing in progress:17 fake_clock.advance_time()18 monkeypatch.setattr(time, 'time', fake_clock.time)19 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)20 assert label in runner.invoke(cli, []).output21def test_progressbar_length_hint(runner, monkeypatch):22 class Hinted(object):23 def __init__(self, n):24 self.items = list(range(n))25 def __length_hint__(self):26 return len(self.items)27 def __iter__(self):28 return self29 def __next__(self):30 if self.items:31 return self.items.pop()32 else:33 raise StopIteration34 next = __next__35 fake_clock = FakeClock()36 @click.command()37 def cli():38 with click.progressbar(Hinted(10), label='test') as progress:39 for thing in progress:40 fake_clock.advance_time()41 monkeypatch.setattr(time, 'time', fake_clock.time)42 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)43 result = runner.invoke(cli, [])44 assert result.exception is None45def test_progressbar_hidden(runner, monkeypatch):46 fake_clock = FakeClock()47 label = 'whatever'48 @click.command()49 def cli():50 with click.progressbar(tuple(range(10)), label=label) as progress:51 for thing in progress:52 fake_clock.advance_time()53 monkeypatch.setattr(time, 'time', fake_clock.time)54 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)55 assert runner.invoke(cli, []).output == ''56def test_choices_list_in_prompt(runner, monkeypatch):57 @click.command()58 @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),59 prompt=True)60 def cli_with_choices(g):61 pass62 @click.command()63 @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),64 prompt=True, show_choices=False)65 def cli_without_choices(g):66 pass67 result = runner.invoke(cli_with_choices, [], input='none')68 assert '(none, day, week, month)' in result.output69 result = runner.invoke(cli_without_choices, [], input='none')70 assert '(none, day, week, month)' not in result.output71def test_secho(runner):72 with runner.isolation() as outstreams:73 click.secho(None, nl=False)74 bytes = outstreams[0].getvalue()75 assert bytes == b''76def test_progressbar_yields_all_items(runner):77 with click.progressbar(range(3)) as progress:78 assert len(list(progress)) == 379def test_progressbar_update(runner, monkeypatch):80 fake_clock = FakeClock()81 @click.command()82 def cli():83 with click.progressbar(range(4)) as progress:84 for _ in progress:85 fake_clock.advance_time()86 print("")87 monkeypatch.setattr(time, 'time', fake_clock.time)88 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)89 output = runner.invoke(cli, []).output90 lines = [line for line in output.split('\n') if '[' in line]91 assert ' 25% 00:00:03' in lines[0]92 assert ' 50% 00:00:02' in lines[1]93 assert ' 75% 00:00:01' in lines[2]...

Full Screen

Full Screen

fake_time_util.py

Source: fake_time_util.py Github

copy

Full Screen

1import asyncio2import contextlib3import functools4import random5from unittest import mock6from trio.testing import MockClock7from pyinstrument import stack_sampler8class FakeClock:9 def __init__(self) -> None:10 self.time = random.random() * 1e611 def get_time(self):12 return self.time13 def sleep(self, duration):14 self.time += duration15@contextlib.contextmanager16def fake_time(fake_clock=None):17 fake_clock = fake_clock or FakeClock()18 stack_sampler.get_stack_sampler().timer_func = fake_clock.get_time19 try:20 with mock.patch("time.sleep", new=fake_clock.sleep):21 yield fake_clock22 finally:23 stack_sampler.get_stack_sampler().timer_func = None24class FakeClockAsyncio:25 # this implementation mostly lifted from26 # https:/​/​aiotools.readthedocs.io/​en/​latest/​_modules/​aiotools/​timer.html#VirtualClock27 # License: https:/​/​github.com/​achimnol/​aiotools/​blob/​800f7f1bce086b0c83658bad8377e6cb1908e22f/​LICENSE28 # Copyright (c) 2017 Joongi Kim29 def __init__(self) -> None:30 self.time = random.random() * 1e631 def get_time(self):32 return self.time33 def sleep(self, duration):34 self.time += duration35 def _virtual_select(self, orig_select, timeout):36 self.time += timeout37 return orig_select(0) # override the timeout to zero38@contextlib.contextmanager39def fake_time_asyncio(loop=None):40 loop = loop or asyncio.get_running_loop()41 fake_clock = FakeClockAsyncio()42 # fmt: off43 with mock.patch.object(44 loop._selector, # type: ignore45 "select",46 new=functools.partial(fake_clock._virtual_select, loop._selector.select), # type: ignore47 ), mock.patch.object(48 loop,49 "time",50 new=fake_clock.get_time51 ), fake_time(fake_clock):52 yield fake_clock53 # fmt: on54class FakeClockTrio:55 def __init__(self, clock: MockClock) -> None:56 self.trio_clock = clock57 def get_time(self):58 return self.trio_clock.current_time()59 def sleep(self, duration):60 self.trio_clock.jump(duration)61@contextlib.contextmanager62def fake_time_trio():63 trio_clock = MockClock(autojump_threshold=0)64 fake_clock = FakeClockTrio(trio_clock)65 with fake_time(fake_clock):...

Full Screen

Full Screen

harness.py

Source: harness.py Github

copy

Full Screen

1import numpy as np2import pandas as pd3from unittest.mock import patch4from pylivetrader.algorithm import Algorithm5from pylivetrader.misc.api_context import LiveTraderAPI6from . import clock, backend7def mock_data(name, dtype, index):8 if dtype == np.dtype('bool'):9 return [True] * len(index)10 elif dtype == np.dtype('float'):11 return [0.5] * len(index)12 elif dtype == np.dtype('object'):13 return ['data'] * len(index)14 elif dtype == np.dtype('int'):15 return [1] * len(index)16class DefaultPipelineHooker:17 def __init__(self):18 pass19 def output(self, context, name):20 pipe = context._pipelines[name]21 index = [22 context.symbol('A'),23 context.symbol('Z'),24 ]25 fakedata = {26 name: mock_data(name, c.dtype, index)27 for name, c in pipe.columns.items()28 }29 return pd.DataFrame(fakedata, index=index)30def noop(*args, **kwargs):31 pass32def run_smoke(algo, before_run_hook=None, pipeline_hook=None):33 fake_clock = clock.FaketimeClock()34 # fake_clock.rollback(1)35 be = backend.Backend(clock=fake_clock)36 a = Algorithm(37 initialize=getattr(algo, 'initialize', noop),38 handle_data=getattr(algo, 'handle_data', noop),39 before_trading_start=getattr(algo, 'before_trading_start', noop),40 backend=be,41 )42 if pipeline_hook is not None:43 def _pipeline_output(name):44 return pipeline_hook.output(a, name)45 a.pipeline_output = _pipeline_output46 with LiveTraderAPI(a), \47 patch('pylivetrader.executor.executor.RealtimeClock') as rc:48 def make_clock(*args, **kwargs):49 # may want to reconfigure clock50 return fake_clock51 rc.side_effect = make_clock52 if before_run_hook is not None:53 before_run_hook(a, be)...

Full Screen

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

How To Automate Mouse Clicks With Selenium Python

Sometimes, in our test code, we need to handle actions that apparently could not be done automatically. For example, some mouse actions such as context click, double click, drag and drop, mouse movements, and some special key down and key up actions. These specific actions could be crucial depending on the project context.

How To Use driver.FindElement And driver.FindElements In Selenium C#

One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.

Why Agile Is Great for Your Business

Agile project management is a great alternative to traditional methods, to address the customer’s needs and the delivery of business value from the beginning of the project. This blog describes the main benefits of Agile for both the customer and the business.

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run freezegun automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful