def registry(num): try: try: fudge.clear_calls() fudge.clear_expectations() exp_order = ExpectedCallOrder(self.fake) reg.remember_expected_call_order(exp_order) eq_(len(reg.get_expected_call_order().keys()), 1) # registered first time on __init__ : exp = ExpectedCall(self.fake, 'callMe', call_order=exp_order) reg.expect_call(exp) reg.expect_call(exp) reg.expect_call(exp) eq_(len(reg.get_expected_calls()), 4) # actual calls: exp() exp() exp() exp() fudge.verify() fudge.clear_expectations() except Exception, er: thread_run.errors.append(er) raise finally: thread_run.waiting -= 1
def test_run_status_bad(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(42) e = assert_raises( CommandFailedError, run.run, client=ssh, logger=logger, args=['foo'], ) assert e.command == 'foo' assert e.exitstatus == 42 assert str(e) == "Command failed on HOST with status 42: 'foo'"
def test_run_log_simple(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo 'bar baz'") in_ = fudge.Fake('ChannelFile(stdin)') out = fudge.Fake('ChannelFile(stdout)') err = fudge.Fake('ChannelFile(stderr)') cmd.returns((in_, out, err)) in_.expects('close').with_args() in_chan = fudge.Fake('channel') in_chan.expects('shutdown_write').with_args() in_.has_attr(channel=in_chan) out.expects('xreadlines').with_args().returns(['foo', 'bar']) err.expects('xreadlines').with_args().returns(['bad']) logger = fudge.Fake('logger') log_err = fudge.Fake('log_err') logger.expects('getChild').with_args('err').returns(log_err) log_err.expects('log').with_args(logging.INFO, '[HOST]: bad') log_out = fudge.Fake('log_out') logger.expects('getChild').with_args('out').returns(log_out) log_out.expects('log').with_args(logging.INFO, '[HOST]: foo') log_out.expects('log').with_args(logging.INFO, '[HOST]: bar') channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(0) r = run.run( client=ssh, logger=logger, args=['foo', 'bar baz'], ) assert r.exitstatus == 0
def test_run_status_bad(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(42) e = assert_raises( run.CommandFailedError, run.run, client=ssh, logger=logger, args=['foo'], ) assert e.command == 'foo' assert e.exitstatus == 42 assert str(e) == "Command failed on HOST with status 42: 'foo'"
def test_run_status_lost(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(-1) transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) transport.expects('is_active').with_args().returns(False) e = assert_raises( run.ConnectionLostError, run.run, client=ssh, logger=logger, args=['foo'], ) assert e.command == 'foo' assert str(e) == "SSH connection was lost: 'foo'"
def tearDown(self): fudge.clear_expectations() fudge.clear_calls() try: os.remove(self.sqlite_db.dbname) except OSError: pass
def test_connect_override_hostkeys(self): self.clear_config() fudge.clear_expectations() sshclient = fudge.Fake('SSHClient') ssh = sshclient.expects_call().with_args().returns_fake() ssh.remember_order() host_keys = fudge.Fake('HostKeys') host_keys.expects('add').with_args( hostname='orchestra.test.newdream.net.invalid', keytype='ssh-rsa', key='frobnitz', ) ssh.expects('get_host_keys').with_args().returns(host_keys) ssh.expects('connect').with_args( hostname='orchestra.test.newdream.net.invalid', username='******', timeout=60, ) transport = ssh.expects('get_transport').with_args().returns_fake() transport.remember_order() transport.expects('set_keepalive').with_args(False) create_key = fudge.Fake('create_key') create_key.expects_call().with_args('ssh-rsa', 'testkey').returns('frobnitz') got = connection.connect( '*****@*****.**', host_key='ssh-rsa testkey', _SSHClient=sshclient, _create_key=create_key, ) assert got is ssh
def test_run(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') ssh.expects('get_transport').returns_fake().expects('getpeername')\ .returns(('name', 22)) run = fudge.Fake('run') args = [ 'something', 'more', ] foo = object() ret = RemoteProcess( client=ssh, args='fakey', ) r = remote.Remote(name='*****@*****.**', ssh=ssh) run.expects_call().with_args( client=fudge.inspector.arg.passes_test(lambda v: v is ssh), args=fudge.inspector.arg.passes_test(lambda v: v is args), foo=fudge.inspector.arg.passes_test(lambda v: v is foo), name=r.shortname, ).returns(ret) # monkey patch ook ook r._runner = run got = r.run( args=args, foo=foo, ) assert got is ret assert got.remote is r
def test_can_connect_to_db(): clear_expectations() db = Db(connection_context) db.connect() assert db.is_connected
def test_run_stderr_pipe(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('read').with_args().returns('one') err.expects('read').with_args().returns('two') err.expects('read').with_args().returns('') logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(0) r = run.run( client=ssh, logger=logger, args=['foo'], stderr=run.PIPE, wait=False, ) assert r.command == 'foo' assert isinstance(r.exitstatus, gevent.event.AsyncResult) assert r.exitstatus.ready() is False assert r.stderr.read() == 'one' assert r.stderr.read() == 'two' assert r.stderr.read() == '' got = r.exitstatus.get() assert got == 0
def test_controller_returns_thread_data_user(): clear_expectations() clear() ctrl = Controller() assert ctrl.user == "some_user"
def test_user_returns_none_when_attribute_error(): clear_expectations() clear() ctrl = Controller() assert not ctrl.user
def test_controller_has_null_user_by_default(): clear_expectations() clear() ctrl = Controller() assert not ctrl.user
def test_settings_will_load_config_ini_retains_config(): clear_expectations() settings = Settings("some_dir") settings.load() assert settings.config
def __enter__(self): fudge.clear_expectations() fudge.clear_calls() self.patches = [] all_fakes = [] for path in self.obj_paths: try: target, attr = path.rsplit('.', 1) except (TypeError, ValueError): raise TypeError( "Need a valid target to patch. You supplied: %r" % path) fake = fudge.Fake(path) all_fakes.append(fake) self.patches.append(patch_object(target, attr, fake)) if len(all_fakes) == 1: return all_fakes[0] else: return all_fakes
def teardown(self): env.clear() # In case tests set env vars that didn't exist previously env.update(self.previous_env) output.update(self.previous_output) shutil.rmtree(self.tmpdir) # Clear Fudge mock expectations...again clear_expectations()
def registry(num): try: try: fudge.clear_calls() fudge.clear_expectations() exp_order = ExpectedCallOrder(self.fake) reg.remember_expected_call_order(exp_order) eq_(len(reg.get_expected_call_order().keys()), 1) # registered first time on __init__ : exp = ExpectedCall(self.fake, "callMe", call_order=exp_order) reg.expect_call(exp) reg.expect_call(exp) reg.expect_call(exp) eq_(len(reg.get_expected_calls()), 4) # actual calls: exp() exp() exp() exp() fudge.verify() fudge.clear_expectations() except Exception, er: thread_run.errors.append(er) raise finally: thread_run.waiting -= 1
def test_arch(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') ssh.expects('get_transport').returns_fake().expects('getpeername')\ .returns(('name', 22)) run = fudge.Fake('run') args = [ 'uname', '-p', ] stdout = StringIO('test_arch') stdout.seek(0) ret = RemoteProcess( client=ssh, args='fakey', ) # status = self._stdout_buf.channel.recv_exit_status() ret._stdout_buf = fudge.Fake() ret._stdout_buf.channel = fudge.Fake() ret._stdout_buf.channel.expects('recv_exit_status').returns(0) ret.stdout = stdout r = remote.Remote(name='*****@*****.**', ssh=ssh) run.expects_call().with_args( client=ssh, args=args, stdout=fudge.inspector.arg.passes_test( lambda v: isinstance(v, OutputType)), name=r.shortname, ).returns(ret) # monkey patch ook ook r._runner = run assert r.arch == 'test_arch'
def test_run_stdin_pipe(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('exit_status_ready').with_args().returns(False) channel.expects('recv_exit_status').with_args().returns(0) r = run.run( client=ssh, logger=logger, args=['foo'], stdin=run.PIPE, wait=False, ) r.stdin.write('bar') assert r.command == 'foo' assert r.poll() is None got = r.wait() assert isinstance(r.returncode, int) assert got == 0
def test_run(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') run = fudge.Fake('run') args = [ 'something', 'more', ] foo = object() ret = RemoteProcess( command='fakey', stdin=None, stdout=None, stderr=None, exitstatus=None, exited=None, ) r = remote.Remote(name='*****@*****.**', ssh=ssh) run.expects_call().with_args( client=fudge.inspector.arg.passes_test(lambda v: v is ssh), args=fudge.inspector.arg.passes_test(lambda v: v is args), foo=fudge.inspector.arg.passes_test(lambda v: v is foo), name=r.shortname, ).returns(ret) # monkey patch ook ook r._runner = run got = r.run( args=args, foo=foo, ) assert got is ret assert got.remote is r
def test_run_status_lost(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') cmd = ssh.expects('exec_command') cmd.with_args("foo") in_ = fudge.Fake('ChannelFile').is_a_stub() out = fudge.Fake('ChannelFile').is_a_stub() err = fudge.Fake('ChannelFile').is_a_stub() cmd.returns((in_, out, err)) out.expects('xreadlines').with_args().returns([]) err.expects('xreadlines').with_args().returns([]) logger = fudge.Fake('logger').is_a_stub() channel = fudge.Fake('channel') out.has_attr(channel=channel) channel.expects('recv_exit_status').with_args().returns(-1) transport = ssh.expects('get_transport').with_args().returns_fake() transport.expects('getpeername').with_args().returns(('HOST', 22)) transport.expects('is_active').with_args().returns(False) e = assert_raises( ConnectionLostError, run.run, client=ssh, logger=logger, args=['foo'], ) assert e.command == 'foo' assert str(e) == "SSH connection to HOST was lost: 'foo'"
def test_settings_can_load_custom_file(): clear_expectations() settings = Settings("some_dir") settings.load("custom.ini") assert settings.config
def test_arch(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') ssh.expects('get_transport').returns_fake().expects('getpeername')\ .returns(('name', 22)) run = fudge.Fake('run') args = [ 'uname', '-m', ] stdout = StringIO('test_arch') stdout.seek(0) ret = RemoteProcess( client=ssh, args='fakey', ) # status = self._stdout_buf.channel.recv_exit_status() ret._stdout_buf = fudge.Fake() ret._stdout_buf.channel = fudge.Fake() ret._stdout_buf.channel.expects('recv_exit_status').returns(0) ret.stdout = stdout r = remote.Remote(name='*****@*****.**', ssh=ssh) run.expects_call().with_args( client=ssh, args=args, stdout=fudge.inspector.arg.passes_test( lambda v: isinstance(v, OutputType)), name=r.shortname, ).returns(ret) # monkey patch ook ook r._runner = run assert r.arch == 'test_arch'
def test_run(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') run = fudge.Fake('run') args = [ 'something', 'more', ] foo = object() ret = RemoteProcess( command='fakey', stdin=None, stdout=None, stderr=None, exitstatus=None, exited=None, ) run.expects_call().with_args( client=fudge.inspector.arg.passes_test(lambda v: v is ssh), args=fudge.inspector.arg.passes_test(lambda v: v is args), foo=fudge.inspector.arg.passes_test(lambda v: v is foo), ).returns(ret) r = remote.Remote(name='*****@*****.**', ssh=ssh) # monkey patch ook ook r._runner = run got = r.run( args=args, foo=foo, ) assert got is ret assert got.remote is r
def inner(self, *args, **kwargs): request = fudge.Fake(HttpRequest) request.has_attr(COOKIES={}) result = func(self, request, *args, **kwargs) fudge.verify() fudge.clear_expectations() return result
def tearDown(self): fudge.clear_expectations() fudge.clear_calls() self.sqlite_db.close() try: os.remove(SQLITE_DATABASE) except OSError: pass
def test_new_action(): clear() clear_expectations() controller = controllers.ProjectController() result = controller.new() assert result == "Create Project"
def test_disconnection_sets_store_to_null(): clear_expectations() db = Db(connection_context) db.connect() db.disconnect() assert not db.store
def test_settings_read_attribute_as_int(): clear_expectations() fake_config = Fake("config") fake_config.expects("get").with_args("name", "setting").returns("10") ss = SettingsSection(None, "name", fake_config) assert ss.as_int("setting") == 10
def test_create_project_provider_replace_tokens_skips_folders(): setup() clear_expectations() prov = CreateProjectProvider() prov.replace_tokens('some_path', project_name="bla") teardown()
def tearDown(self): try: os.remove('test_database.db') except OSError: pass fudge.clear_calls() fudge.clear_expectations()
def test_disconnection_calls_close(): clear_expectations() db = Db(connection_context) db.connect() db.disconnect() assert not db.is_connected
def __exit__(self, exc_type, exc_val, exc_tb): try: if not exc_type: fudge.verify() finally: for p in self.patches: p.restore() fudge.clear_expectations()
def test_host_key(self): fudge.clear_expectations() ssh = fudge.Fake('SSHConnection') key = ssh.expects('get_transport').returns_fake().expects( 'get_remote_server_key').returns_fake() key.expects('get_name').returns('key_type') key.expects('get_base64').returns('test ssh key') r = remote.Remote(name='*****@*****.**', ssh=ssh) assert r.host_key == 'key_type test ssh key'
def setUp(self): fudge.clear_expectations() # from previous tests fake_setup = fudge.Fake('xmlrpclib.ServerProxy', expect_call=True) fake_api = ( fake_setup.returns_fake() .expects('login').with_arg_count(3) .provides('execute').returns(RESPONSE_IRMODEL) ) self.patched = fudge.patch_object(xmlrpclib, 'ServerProxy', fake_setup)
def test_read_attribute_before_load_gives_error(): clear_expectations() settings = Settings("some_dir") try: assert settings.SomeSection.SomeAttribute except RuntimeError, err: assert str(err) == "You can't use any settings before loading a config file. Please use the load method." return
def test_str(self): fudge.clear_expectations() r1 = remote.Remote('r1', ssh=fudge.Fake('SSH')) r2 = remote.Remote('r2', ssh=fudge.Fake('SSH')) c = cluster.Cluster(remotes=[ (r1, ['foo', 'bar']), (r2, ['baz']), ], ) assert str(c) == "r1[foo,bar] r2[baz]"
def test_task_will_invoke_provided_class(): def foo(): pass fake = Fake() fake.expects("__init__").with_args(foo) fudge.clear_calls() fudge.clear_expectations() foo = decorators.task(foo, task_class=fake) fudge.verify()
def test_task_passes_args_to_the_task_class(): random_vars = ("some text", random.randint(100, 200)) def foo(): pass fake = Fake() fake.expects("__init__").with_args(foo, *random_vars) fudge.clear_calls() fudge.clear_expectations() foo = decorators.task(foo, task_class=fake, *random_vars) fudge.verify()
def test_repr(self): fudge.clear_expectations() r1 = remote.Remote('r1', ssh=fudge.Fake('SSH')) r2 = remote.Remote('r2', ssh=fudge.Fake('SSH')) c = cluster.Cluster( remotes=[ (r1, ['foo', 'bar']), (r2, ['baz']), ], ) assert repr(c) == "Cluster(remotes=[[Remote(name='r1'), ['foo', 'bar']], [Remote(name='r2'), ['baz']]])" # noqa
def test_only_two(self): fudge.clear_expectations() r1 = fudge.Fake('r1') r2 = fudge.Fake('r2') r3 = fudge.Fake('r3') c = cluster.Cluster(remotes=[ (r1, ['foo', 'bar']), (r2, ['bar']), (r3, ['foo']), ], ) c_both = c.only('foo', 'bar') assert c_both.remotes, {r1: ['foo' == 'bar']}
def test_exclude_none(self): fudge.clear_expectations() r1 = fudge.Fake('r1') r2 = fudge.Fake('r2') r3 = fudge.Fake('r3') c = cluster.Cluster(remotes=[ (r1, ['foo', 'bar']), (r2, ['bar']), (r3, ['foo']), ], ) c_none = c.exclude('impossible') assert c_none.remotes == {r1: ['foo', 'bar'], r2: ['bar'], r3: ['foo']}
def test_exclude_match(self): fudge.clear_expectations() r1 = fudge.Fake('r1') r2 = fudge.Fake('r2') r3 = fudge.Fake('r3') c = cluster.Cluster(remotes=[ (r1, ['foo', 'bar']), (r2, ['bar']), (r3, ['foo']), ], ) c_foo = c.exclude('foo', lambda role: role.startswith('b')) assert c_foo.remotes == {r2: ['bar'], r3: ['foo']}
def test_only_one(self): fudge.clear_expectations() r1 = fudge.Fake('r1') r2 = fudge.Fake('r2') r3 = fudge.Fake('r3') c = cluster.Cluster(remotes=[ (r1, ['foo', 'bar']), (r2, ['bar']), (r3, ['foo']), ], ) c_foo = c.only('foo') assert c_foo.remotes == {r1: ['foo', 'bar'], r3: ['foo']}
def test_exclude_two(self): fudge.clear_expectations() r1 = fudge.Fake('r1') r2 = fudge.Fake('r2') r3 = fudge.Fake('r3') c = cluster.Cluster(remotes=[ (r1, ['foo', 'bar']), (r2, ['bar']), (r3, ['foo']), ], ) c_both = c.exclude('foo', 'bar') assert c_both.remotes == {r2: ['bar'], r3: ['foo']}
def test_cache_hit(self): response = datasources.pubmed.filter_pmids(gold_pmids, test_data_geo_filter) patched = fudge.patch_object("EUtils.HistoryClient", "HistoryClient", get_a_FakeHistoryClient_hit()) fudge.clear_calls() try: response = datasources.pubmed.filter_pmids(gold_pmids, test_data_geo_filter) fudge.verify() finally: patched.restore() fudge.clear_expectations()
def _disabled_test_cache_miss(self): TimedCache().is_bypass_cache(True) patched = fudge.patch_object("EUtils.HistoryClient", "HistoryClient", get_a_FakeHistoryClient_miss()) fudge.clear_calls() try: response = datasources.pubmed.filter_pmids(gold_pmids, test_data_geo_filter) fudge.verify() finally: patched.restore() fudge.clear_expectations() TimedCache().is_bypass_cache(False)
def setup(self): # Clear Fudge mock expectations clear_expectations() # Copy env, output for restoration in teardown self.previous_env = copy.deepcopy(env) # Deepcopy doesn't work well on AliasDicts; but they're only one layer # deep anyways, so... self.previous_output = output.items() # Allow hooks from subclasses here for setting env vars (so they get # purged correctly in teardown()) self.env_setup() # Temporary local file dir self.tmpdir = tempfile.mkdtemp()
def test_global_clear_expectations(self): exp = ExpectedCall(self.fake, 'callMe') exp() eq_(len(self.reg.get_expected_calls()), 1) exp_order = ExpectedCallOrder(self.fake) self.reg.remember_expected_call_order(exp_order) eq_(self.reg.get_expected_call_order().keys(), [self.fake]) fudge.clear_expectations() eq_(len(self.reg.get_expected_calls()), 0, "clear_expectations() should reset expectations") eq_(len(self.reg.get_expected_call_order().keys()), 0, "clear_expectations() should reset expected call order")
def setup(self): # Clear Fudge mock expectations clear_expectations() # Copy env, output for restoration in teardown self.previous_env = copy.deepcopy(env) # Deepcopy doesn't work well on AliasDicts; but they're only one layer # deep anyways, so... self.previous_output = output.items() # Set up default networking for test server env.disable_known_hosts = True interpret_host_string('%s@%s:%s' % (USER, HOST, PORT)) env.password = PASSWORDS[USER] # Command response mocking is easier without having to account for # shell wrapping everywhere. env.use_shell = False
def test_fastprint_calls_puts(): """ fastprint() is just an alias to puts() """ text = "Some output" fake_puts = Fake('puts', expect_call=True).with_args(text=text, show_prefix=False, end="", flush=True) with patched_context(utils, 'puts', fake_puts): try: fastprint(text) verify() finally: clear_expectations()