Example #1
0
    def test_connect_does_not_prompt_password_when_ssh_raises_channel_exception(self):
        def raise_channel_exception_once(*args, **kwargs):
            if raise_channel_exception_once.should_raise_channel_exception:
                raise_channel_exception_once.should_raise_channel_exception = False
                raise ssh.ChannelException(2, 'Connect failed')
        raise_channel_exception_once.should_raise_channel_exception = True

        def generate_fake_client():
            fake_client = Fake('SSHClient', allows_any_call=True, expect_call=True)
            fake_client.provides('connect').calls(raise_channel_exception_once)
            return fake_client

        fake_ssh = Fake('ssh', allows_any_call=True)
        fake_ssh.provides('SSHClient').calls(generate_fake_client)
        # We need the real exceptions here to preserve the inheritence structure
        fake_ssh.SSHException = ssh.SSHException
        fake_ssh.ChannelException = ssh.ChannelException
        patched_connect = patch_object('fabric.network', 'ssh', fake_ssh)
        patched_password = patch_object('fabric.network', 'prompt_for_password', Fake('prompt_for_password', callable = True).times_called(0))
        try:
            connect('user', 'localhost', 22, HostConnectionCache())
        finally:
            # Restore ssh
            patched_connect.restore()
            patched_password.restore()
Example #2
0
    def test_can_be_process_request_render_500_template(self):

        settings.DEBUG = False
        mapper_fake = fudge.Fake().expects("match").with_args("shouldBeUri").returns({"controller":"shouldBeController"})

        FakeTorneiraDispatcher = fudge.Fake("TorneiraDispatcher").expects("__init__")
        FakeTorneiraDispatcher.returns_fake().expects("getMapper").returns(mapper_fake).expects("getController").raises(ValueError())

        FakeBaseController = fudge.Fake("BaseController").expects("__init__")
        FakeBaseController.returns_fake().expects("render_to_template").with_args("/500.html").returns("shouldBeTemplate")

        patches = [
            fudge.patch_object(server, "TorneiraDispatcher", FakeTorneiraDispatcher),
            fudge.patch_object(server, "BaseController", FakeBaseController),
        ]

        write_fake = fudge.Fake(callable=True).with_args("shouldBeTemplate")

        try:
            handler = server.TorneiraHandler(self.application_fake, self.request_fake)

            with fudge.patched_context(handler, "write", write_fake):
                handler.process_request()

        finally:

            for p in patches:
                p.restore() 

            settings.DEBUG = True               
 def setup_fudge_mocks(self):
     self.clear_expectations_mock = fudge.Fake('clear_expectations').is_callable()
     self.clear_expectations_patch = fudge.patch_object('fudge', 'clear_expectations', self.clear_expectations_mock)
     self.clear_calls_mock = fudge.Fake('clear_calls').is_callable()
     self.clear_calls_patch = fudge.patch_object('fudge', 'clear_calls', self.clear_calls_mock)
     self.verify_mock = fudge.Fake('verify').is_callable()
     self.verify_patch = fudge.patch_object('fudge', 'verify', self.verify_mock)
Example #4
0
def test_context_manager(fake):
    fudge.patch_object(statsd.StatsClient, 'timing', mock_statsd_method)
    k = kruxstatsd.StatsClient('js', env='prod')
    fake.expects_call().with_args('prod.js.mytimer.%s' % (hostname, ),
                                  arg.any(), 1)
    with k.timer('mytimer'):
        assert True
Example #5
0
def setUpPackage(self):

    mock_get = fudge.Fake().is_callable().returns(
        fudge.Fake().has_attr(text='<title>Howdy Dammit</title>')
    )

    self.patch_request = fudge.patch_object(
        'auctions.models.requests', 'get', mock_get
    )

    mock_create = fudge.Fake().has_attr(id='dammit')

    mock_stripe = (
        fudge.Fake().provides('create').returns(mock_create)
    )

    self.patch_stripe = fudge.patch_object(
        'auctions.models.stripe', 'Charge', mock_stripe)

    fake_items = [fudge.Fake().has_attr(
        transaction_status='SUCCESS',
        payout_item_id='Howdy'),
    ]

    mock_paypal = (
        fudge.Fake().is_callable().returns(
            fudge.Fake().provides('create').returns(True)
            .has_attr(items=fake_items)
        )
    )

    self.patch_paypal = fudge.patch_object(
        'auctions.models', 'PaypalPayout', mock_paypal
    )
Example #6
0
    def test_web_transport_valid_password(self):
        fake_urlopen = fudge.Fake('urlopen')
        fake_response = fudge.Fake('fake_response')
        fake_urlencode = fudge.Fake('urlencode')

        urllib2 = fudge.patch_object("urllib2", "urlopen", fake_urlopen)
        fake_urlopen.expects_call().returns(fake_response)
        fake_response.expects("read").returns(
            '{"message": "success", "status": "ok"}')

        message = sendgrid.Message("*****@*****.**", "subject1",
                                   "plain_text", "html")
        message.add_to("*****@*****.**")

        urllib = fudge.patch_object("urllib", "urlencode", fake_urlencode)
        fake_urlencode.expects_call().with_args(
            {
                'from': '*****@*****.**',
                'api_user': '******',
                'text': 'plain_text',
                'to': ['*****@*****.**'],
                'toname': [''],
                'html': 'html',
                'date': message.date,
                'api_key': 'password',
                'subject': 'subject1'
            }, 1).returns("")

        web_transport = web.Http('username', 'password')
        self.assertTrue(web_transport.send(message))

        urllib.restore()
        urllib2.restore()
Example #7
0
def test_context_manager(fake):
    fudge.patch_object(statsd.StatsClient, 'timing', mock_statsd_method)
    k = kruxstatsd.StatsClient('js', env='prod')
    fake.expects_call().with_args(
        'prod.js.mytimer.%s' % (hostname,), arg.any(), 1)
    with k.timer('mytimer'):
        assert True
Example #8
0
    def test_connect_does_not_prompt_password_when_ssh_raises_channel_exception(
            self):
        def raise_channel_exception_once(*args, **kwargs):
            if raise_channel_exception_once.should_raise_channel_exception:
                raise_channel_exception_once.should_raise_channel_exception = False
                raise ssh.ChannelException(2, 'Connect failed')

        raise_channel_exception_once.should_raise_channel_exception = True

        def generate_fake_client():
            fake_client = Fake('SSHClient',
                               allows_any_call=True,
                               expect_call=True)
            fake_client.provides('connect').calls(raise_channel_exception_once)
            return fake_client

        fake_ssh = Fake('ssh', allows_any_call=True)
        fake_ssh.provides('SSHClient').calls(generate_fake_client)
        # We need the real exceptions here to preserve the inheritence structure
        fake_ssh.SSHException = ssh.SSHException
        fake_ssh.ChannelException = ssh.ChannelException
        patched_connect = patch_object('fabric.network', 'ssh', fake_ssh)
        patched_password = patch_object(
            'fabric.network', 'prompt_for_password',
            Fake('prompt_for_password', callable=True).times_called(0))
        try:
            connect('user', 'localhost', 22, HostConnectionCache())
        finally:
            # Restore ssh
            patched_connect.restore()
            patched_password.restore()
Example #9
0
    def setUp(self):
        super(BotTest, self).setUp()

        fake_logger = fudge.Fake('logger', callable=True).returns_fake().is_a_stub()
        self.logger_patch = fudge.patch_object(Bot, '_get_logger', fake_logger)

        fake_connect = fudge.Fake('connect', callable=True).returns(True)
        self.connect_patch = fudge.patch_object(Bot, 'connect', fake_connect)
Example #10
0
    def setUp(self):
        super(BotTest, self).setUp()

        fake_logger = fudge.Fake('logger',
                                 callable=True).returns_fake().is_a_stub()
        self.logger_patch = fudge.patch_object(Bot, '_get_logger', fake_logger)

        fake_connect = fudge.Fake('connect', callable=True).returns(True)
        self.connect_patch = fudge.patch_object(Bot, 'connect', fake_connect)
Example #11
0
    def setUp(self):
        self.messages = []
        def msg(*a, **kw):
            self.messages.append([a, sorted(kw.items()),
                ])

        self.restore2 = fudge.patch_object(log, 'msg', msg)
Example #12
0
def setUpPackage(self):
    # mock stripe Customer
    mock_id = fudge.Fake().has_attr(id='dammit')
    mock_customer = (fudge.Fake().provides('create').returns(mock_id))
    self.patch_stripe = fudge.patch_object('payments.utils.stripe', 'Customer',
                                           mock_customer)

    # mock stripe Event
    evt_resp = json.loads(payment_created)
    mock_event = (fudge.Fake().provides('retrieve').has_attr(
        verified=True).returns(evt_resp))
    self.patch_stripe = fudge.patch_object('payments.utils.stripe', 'Event',
                                           mock_event)

    # mock stripe account_id
    setup_mock_account(verification=account_verified)
    def test_set_template_no_template_string(self, mock_get_template_context):
        # Create occurrence
        occurrence_start = datetime(2015, 2, 1, 12, 00)
        occurrence_end = datetime(2015, 2, 1, 18, 00)
        occ = Occurrence.from_event(self.event, occurrence_start, occurrence_end)

        # getting context returns mock context string
        mock_get_template_context.is_callable().returns('context')

        # Expact the default template to be set on the occurrence
        occ.default_a_field_template = 'default jinja template'

        # Jinja template engine is selected and is passed the template string, render is called on the template
        mock_jinja_engine = fudge.Fake()
        mock_template = mock_jinja_engine.expects('from_string').with_args('default jinja template').returns_fake()
        mock_template.expects('render').with_args('context').returns('rendered context')

        mock_engines = {
            'jinja2': mock_jinja_engine
        }

        patched_engines = fudge.patch_object(events_models, 'engines', mock_engines)

        # call set_template
        occ.set_template('a_field')

        self.assertEqual(occ.a_field, 'rendered context')

        patched_engines.restore()
    def test_smtp_transport_valid_password(self):
        smtp_login = fudge.patch_object("smtplib.SMTP", "login", fudge.Fake('smtp.login')\
            .expects_call().with_args('username', 'password'))
        smtp_sendmail = fudge.patch_object("smtplib.SMTP", "sendmail", fudge.Fake('smtp.sendmail')\
            .expects_call())
        smtp_quit = fudge.patch_object("smtplib.SMTP", "quit", fudge.Fake('smtp.quit')\
            .expects_call())

        message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html")
        message.add_to("*****@*****.**", "John Doe")
        smtp_transport = smtp.Smtp('username', 'password', tls=False)
        self.assertTrue(smtp_transport.send(message))

        smtp_login.restore()
        smtp_sendmail.restore()
        smtp_quit.restore()
Example #15
0
def test_patch_path():
    from os.path import join as orig_join
    patched = fudge.patch_object("os.path", "join", Freddie())
    import os.path
    eq_(type(os.path.join), type(Freddie()))
    patched.restore()
    eq_(type(os.path.join), type(orig_join))
    def setUp(self):
        self.original_logs = Bot.LOGS
        super(BotTest, self).setUp()

        fake_logger = fudge.Fake('logger', callable=True).returns_fake().is_a_stub()
        self.logger_patch = fudge.patch_object(Bot, '_get_logger', fake_logger)

        self.connect_patch = None
Example #17
0
def setUpPackage(self):

    mock_get = fudge.Fake().is_callable().returns(
        fudge.Fake().has_attr(text='<title>Howdy Dammit</title>'))

    self.patch_request = fudge.patch_object('auctions.models.requests', 'get',
                                            mock_get)

    mock_create = fudge.Fake().has_attr(id='dammit')

    mock_stripe = (fudge.Fake().provides('create').returns(mock_create))

    self.patch_stripe = fudge.patch_object('payments.utils.stripe', 'Charge',
                                           mock_stripe)

    self.patch_stripe = fudge.patch_object('payments.utils.stripe', 'Refund',
                                           mock_stripe)
Example #18
0
def test_patch_obj():
    class holder:
        exc = Exception()
    
    patched = fudge.patch_object(holder, "exc", Freddie())
    eq_(type(holder.exc), type(Freddie()))
    patched.restore()
    eq_(type(holder.exc), type(Exception()))
Example #19
0
    def test_smtp_transport_valid_password(self):
        smtp_login = fudge.patch_object("smtplib.SMTP", "login", fudge.Fake('smtp.login')\
            .expects_call().with_args('username', 'password'))
        smtp_sendmail = fudge.patch_object("smtplib.SMTP", "sendmail", fudge.Fake('smtp.sendmail')\
            .expects_call())
        smtp_quit = fudge.patch_object("smtplib.SMTP", "quit", fudge.Fake('smtp.quit')\
            .expects_call())

        message = sendgrid.Message("*****@*****.**", "subject1",
                                   "plain_text", "html")
        message.add_to("*****@*****.**", "John Doe")
        smtp_transport = smtp.Smtp('username', 'password', tls=False)
        self.assertTrue(smtp_transport.send(message))

        smtp_login.restore()
        smtp_sendmail.restore()
        smtp_quit.restore()
Example #20
0
 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_smtp_transport_wrong_password(self):
        fake_login = fudge.Fake('smtp.login')
        smtp_login = fudge.patch_object("smtplib.SMTP", "login", fake_login)
        fake_login.expects_call().with_args('username', 'password').raises(Exception("SMTP authentication error"))

        message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html")
        smtp_transport = smtp.Smtp('username', 'password', tls=False)
        self.assertRaises(sendgrid.exceptions.SGServiceException, smtp_transport.send, message)

        smtp_login.restore()
Example #22
0
def setup_mock_account(verification):
    account_id = 'acct_12QkqYGSOD4VcegJ'
    mock_ext_acct = (fudge.Fake().has_attr(
        external_account='').provides('save').is_a_stub())
    mock_ext_acct.has_attr(id=account_id)
    mock_ext_acct.has_attr(verification=json.loads(verification))

    mock_keys = {
        "id": account_id,
        "keys": {
            "secret": "sk_live_AxSI9q6ieYWjGIeRbURf6EG0",
            "publishable": "pk_live_h9xguYGf2GcfytemKs5tHrtg"
        }
    }

    mock_account = (fudge.Fake().provides('create').returns(
        mock_keys).provides('retrieve').returns(mock_ext_acct))

    fudge.patch_object('payments.utils.stripe', 'Account', mock_account)
Example #23
0
def test_staticmethod_descriptor():
    class Klass(object):
        @staticmethod
        def static():
            return 'OK'
    fake = fudge.Fake()
    p = fudge.patch_object(Klass, 'static', fake)
    eq_(Klass.static, fake)
    p.restore()
    eq_(Klass.static(), 'OK')
Example #24
0
def setUpPackage(self):
    # mock stripe Customer
    mock_id = fudge.Fake().has_attr(id='dammit')
    mock_customer = (
        fudge.Fake().provides('create').returns(mock_id)
    )
    self.patch_stripe = fudge.patch_object(
        'payments.utils.stripe', 'Customer', mock_customer)

    # mock stripe Event
    evt_resp = json.loads(payment_created)
    mock_event = (
        fudge.Fake().provides('retrieve').has_attr(verified=True)
        .returns(evt_resp)
    )
    self.patch_stripe = fudge.patch_object(
        'payments.utils.stripe', 'Event', mock_event)

    # mock stripe account_id
    setup_mock_account(verification=account_verified)
Example #25
0
def setup_mock_account(verification):
    account_id = 'acct_12QkqYGSOD4VcegJ'
    mock_ext_acct = (
        fudge.Fake().has_attr(external_account='')
                    .provides('save').is_a_stub()
    )
    mock_ext_acct.has_attr(id=account_id)
    mock_ext_acct.has_attr(verification=json.loads(verification))

    mock_keys = {"id": account_id,
                 "keys": {"secret": "sk_live_AxSI9q6ieYWjGIeRbURf6EG0",
                          "publishable": "pk_live_h9xguYGf2GcfytemKs5tHrtg"}}

    mock_account = (
        fudge.Fake().provides('create').returns(mock_keys)
        .provides('retrieve').returns(mock_ext_acct)
    )

    fudge.patch_object(
        'payments.utils.stripe', 'Account', mock_account)
Example #26
0
def test_patch_builtin():
    import datetime
    orig_datetime = datetime.datetime
    now = datetime.datetime(2010, 11, 4, 8, 19, 11, 28778)
    fake = fudge.Fake('now').is_callable().returns(now)
    patched = fudge.patch_object(datetime.datetime, 'now', fake)
    try:
        eq_(datetime.datetime.now(), now)
    finally:
        patched.restore()
    eq_(datetime.datetime.now, orig_datetime.now)
Example #27
0
    def setUp(self):
        fudge.clear_expectations()

        # We need to mock out run, local, and put

        self.fake_run = fudge.Fake('project.run', callable=True)
        self.patched_run = fudge.patch_object(project, 'run', self.fake_run)

        self.fake_local = fudge.Fake('local', callable=True)
        self.patched_local = fudge.patch_object(project, 'local',
                                                self.fake_local)

        self.fake_put = fudge.Fake('put', callable=True)
        self.patched_put = fudge.patch_object(project, 'put', self.fake_put)

        # We don't want to create temp folders
        self.fake_mkdtemp = fudge.Fake('mkdtemp',
                                       expect_call=True).returns(self.fake_tmp)
        self.patched_mkdtemp = fudge.patch_object(project, 'mkdtemp',
                                                  self.fake_mkdtemp)
Example #28
0
def test_base_class_attribute():
    class Base(object):
        foo = 'bar'
    class Main(Base):
        pass
    fake = fudge.Fake()
    p = fudge.patch_object(Main, 'foo', fake)
    eq_(Main.foo, fake)
    eq_(Base.foo, 'bar')
    p.restore()
    eq_(Main.foo, 'bar')
    assert 'foo' not in Main.__dict__, ('Main.foo was not restored correctly')
Example #29
0
 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()
Example #30
0
 def test_if_new_directory_is_created_and_instantly_removed_error_does_not_happen(self):
     self.init_repo('testrepo')
     monitor = RepositorySet(self.basedir)
     fake = fudge.Fake('isdir', callable=True).returns(True)
     patch = fudge.patch_object(os.path, 'isdir', fake)
     try:
         monitor.check()
         os.mkdir(os.path.join(self.basedir, 'testrepo', 'testdir'))
         os.rmdir(os.path.join(self.basedir, 'testrepo', 'testdir'))
         monitor.check()
     finally:
         patch.restore()
Example #31
0
def test_patch_builtin_as_string():
    import datetime
    orig_datetime = datetime.datetime
    now = datetime.datetime(2006, 11, 4, 8, 19, 11, 28778)
    fake_dt = fudge.Fake('datetime').provides('now').returns(now)
    patched = fudge.patch_object('datetime', 'datetime', fake_dt)
    try:
        # timetuple is a workaround for strange Jython behavior!
        eq_(datetime.datetime.now().timetuple(), now.timetuple())
    finally:
        patched.restore()
    eq_(datetime.datetime.now, orig_datetime.now)
Example #32
0
def setUpPackage(self):

    mock_get = fudge.Fake().is_callable().returns(
        fudge.Fake().has_attr(text='<title>Howdy Dammit</title>')
    )

    self.patch_request = fudge.patch_object(
        'auctions.models.requests', 'get', mock_get
    )

    mock_create = fudge.Fake().has_attr(id='dammit')

    mock_stripe = (
        fudge.Fake().provides('create').returns(mock_create)
    )

    self.patch_stripe = fudge.patch_object(
        'payments.utils.stripe', 'Charge', mock_stripe)

    self.patch_stripe = fudge.patch_object(
        'payments.utils.stripe', 'Refund', mock_stripe)
Example #33
0
    def test_can_be_get_session(self):
        
        fudge.clear_expectations()
        fudge.clear_calls()
        
        settings.DATABASE_ENGINE = "shouldBeDataBase"
        settings.DATABASE_POOL_SIZE = "shouldBePoolSize"
        
        FakeTimerProxy = fudge.Fake("TimerProxy").expects("__init__")
        timer_proxy_instance = FakeTimerProxy.returns_fake()

        create_engine_fake = fudge.Fake(callable=True).with_args("shouldBeDataBase", 
            pool_size="shouldBePoolSize", 
            pool_recycle=300, 
            proxy=timer_proxy_instance
        ).returns("shouldBeEngine")
        
        sessionmaker_fake = fudge.Fake(callable=True).with_args(autocommit=True, 
            autoflush=False, 
            expire_on_commit=False, 
            bind="shouldBeEngine"
        ).returns("shouldBeScopedSession")

        scoped_session_fake = fudge.Fake(callable=True).with_args("shouldBeScopedSession").returns("shouldBeSession")

        patches = [
            fudge.patch_object(meta, "TimerProxy", FakeTimerProxy),
            fudge.patch_object(meta, "create_engine", create_engine_fake),
            fudge.patch_object(meta, "sessionmaker", sessionmaker_fake),
            fudge.patch_object(meta, "scoped_session", scoped_session_fake)
        ]

        try:
            session = meta.TorneiraSession()
            self.assertEqual(session, "shouldBeSession")
        finally:
            fudge.verify()
            
            for p in patches:
                p.restore()
Example #34
0
    def setUp(self):
        super(BaseDonationFormViewTestCase, self).setUp()
        # TODO: move this to armstrong.dev
        self.client = Client()

        # TODO: make this based off of class name and move into armstrong.dev
        settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__),
                                               "_templates"), )
        self.client
        self.patches = [
            fudge.patch_object(views, "backends", self.get_backend_stub())
        ]
        fudge.clear_calls()
Example #35
0
 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)
Example #36
0
 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()
Example #37
0
    def inner(self):
        random_text = "Some Random Text (%d)" % random.randint(1000, 2000)
        backend = self.get_backend_stub(successful=False, reason=random_text)
        self.patches = [
            fudge.patch_object(views, "backends", backend),
        ]
        fudge.clear_calls()

        data = self.random_post_data
        response = self.client.post(self.url, data)
        backend_response = backend.get_backend().purchase()["response"]
        func(self, response, random_text=random_text,
                backend_response=backend_response)
Example #38
0
 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)            
Example #39
0
    def test_smtp_transport_wrong_password(self):
        fake_login = fudge.Fake('smtp.login')
        smtp_login = fudge.patch_object("smtplib.SMTP", "login", fake_login)
        fake_login.expects_call().with_args('username', 'password').raises(
            Exception("SMTP authentication error"))

        message = sendgrid.Message("*****@*****.**", "subject1",
                                   "plain_text", "html")
        smtp_transport = smtp.Smtp('username', 'password', tls=False)
        self.assertRaises(sendgrid.exceptions.SGServiceException,
                          smtp_transport.send, message)

        smtp_login.restore()
Example #40
0
def test_bound_methods():
    class Klass(object):
        def method(self):
            return 'foozilate'
    instance = Klass()
    fake = fudge.Fake()
    p = fudge.patch_object(instance, 'method', fake)
    eq_(instance.method, fake)
    p.restore()
    eq_(instance.method(), Klass().method())
    assert inspect.ismethod(instance.method)
    assert 'method' not in instance.__dict__, (
                            'instance.method was not restored correctly')
Example #41
0
def test_property():
    class Klass(object):
        @property
        def prop(self):
            return 'OK'
    exact_prop = Klass.prop
    instance = Klass()
    fake = fudge.Fake()
    p = fudge.patch_object(instance, 'prop', fake)
    eq_(instance.prop, fake)
    p.restore()
    eq_(instance.prop, 'OK')
    eq_(Klass.prop, exact_prop)
    def test_web_transport_valid_password(self):
        fake_urlopen = fudge.Fake('urlopen')
        fake_response = fudge.Fake('fake_response')
        fake_urlencode = fudge.Fake('urlencode')

        urllib2 = fudge.patch_object("urllib2", "urlopen", fake_urlopen)
        fake_urlopen.expects_call().returns(fake_response)
        fake_response.expects("read").returns('{"message": "success", "status": "ok"}')

        message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html")
        message.add_to("*****@*****.**")

        urllib = fudge.patch_object("urllib", "urlencode", fake_urlencode)
        fake_urlencode.expects_call().with_args({'from': '*****@*****.**', 'api_user': '******', 'text': 'plain_text',
                                                 'to': ['*****@*****.**'], 'html': 'html', 'date': message.date,
                                                 'api_key': 'password', 'subject': 'subject1'}, 1).returns("")

        web_transport = web.Http('username', 'password')
        self.assertTrue(web_transport.send(message))

        urllib.restore()
        urllib2.restore()
Example #43
0
        def test():
            jsPackages = athena.allJavascriptPackages()
            rr = example.AthenaPage(jsModules=athena.MappingResource(jsPackages))
            rr._becomeLive(url.URL('/app'))
            rendered = yield flat.flatten(rr)
            self.assertSubstring('Rate: 50', rendered)

            # set the rate to be too infrequent to have any race possibilities
            # during this test
            rr.rate = 0.00001 # = 100000 seconds between updates

            rr.wid.setFilter(0)
            self.assertEqual(rr.wid.filter, 0)

            rr.wid.liveFragmentChildren = []


            callRemote = fudge.Fake("callRemote", expect_call=True)
            callRemote.with_args("number", 486000).returns(defer.succeed(u'ok'))
            fudge.patch_object(rr.wid, 'callRemote', callRemote)

            random.seed(10)

            # make two calls to random() with this seed.  They should return
            # the tested values, using Python's documented PRNG: Mersenne
            # Twister, and this seed.

            num = yield rr.wid.number()
            self.assertEqual(num, 614262)

            num = yield rr.wid.number()
            self.assertEqual(num, 486000)

            fudge.verify()

            rr.wid._athenaDetachServer()
            rr.action_close(None)
            defer.returnValue(None)
    def test_web_transport_wrong_password(self):
        fake_urlopen = fudge.Fake('urlopen')
        fake_response = fudge.Fake('fake_response')
        urllib = fudge.patch_object("urllib2", "urlopen", fake_urlopen)
        fake_urlopen.expects_call().returns(fake_response)
        fake_response.expects("read").raises(FakeException('{"message": "error", "errors": "Bad username / password"}'))

        message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html")
        message.add_to("*****@*****.**")

        web_transport = web.Http('username', 'password')
        self.assertRaises(sendgrid.exceptions.SGServiceException, web_transport.send, message)

        urllib.restore()
Example #45
0
    def patch_context_manager(self, module_name, object_name):
        type_mock = fudge.Fake(object_name)
        object_mock = type_mock.is_callable().returns_fake().is_a_stub()

        class FakeContext(object):
            def __enter__(self):
                return object_mock

            def __exit__(self, type, value, traceback):
                pass

        object_patch = fudge.patch_object(module_name, object_name, FakeContext)
        FudgeTestCase.patches.append(object_patch)
        return object_mock
Example #46
0
    def setUp(self):
        super(BaseDonationFormViewTestCase, self).setUp()
        # TODO: move this to armstrong.dev
        self.client = Client()

        # TODO: make this based off of class name and move into armstrong.dev
        settings.TEMPLATE_DIRS = (
            os.path.join(os.path.dirname(__file__), "_templates"),
        )
        self.client
        self.patches = [
            fudge.patch_object(views, "backends", self.get_backend_stub())
        ]
        fudge.clear_calls()
Example #47
0
 def test_can_be_run(self):
     
     fudge.clear_expectations()
     fudge.clear_calls()
     
     FakeApplication = fudge.Fake("Application").expects("__init__").with_args([
         (r"/media/(.*)", tornado.web.StaticFileHandler, {"path": "shouldBeMediaDir"}),
         (r"/.*", server.TorneiraHandler)
     ], cookie_secret=settings.COOKIE_SECRET, debug=True)
     
     application_instance = FakeApplication.returns_fake()
     
     FakeServer = fudge.Fake("HTTPServer").expects("__init__").with_args(application_instance, xheaders="shouldBeXHeaders")
     server_instance = FakeServer.returns_fake().expects("listen").with_args("shouldBePort")
     
     FakeIOLoop = fudge.Fake("IOLoop").expects("instance")
     FakeIOLoop.returns_fake().expects("start")
     
     patches = [
         fudge.patch_object(server, "Application", FakeApplication),
         fudge.patch_object(server, "HTTPServer", FakeServer),
         fudge.patch_object(server, "IOLoop", FakeIOLoop)
     ]
     
     try:
         torneira_server = server.TorneiraServer("shouldBePidfile", "shouldBePort", "shouldBeMediaDir", xheaders="shouldBeXHeaders")
         
         self.assertEqual(torneira_server.pidfile, "shouldBePidfile")
         self.assertEqual(torneira_server.media_dir, "shouldBeMediaDir")
         
         torneira_server.run()
         
     finally:
         fudge.verify()
         
         for p in patches:
             p.restore()
Example #48
0
    def test_can_be_process_request(self):

        match = {
            "controller":"shouldBecontroller", 
            "action":"shouldBeAction"
        }
        
        controller_fake = fudge.Fake().expects("shouldBeAction").returns("shouldBeResponse")
        mapper_fake = fudge.Fake().expects("match").with_args("shouldBeUri").returns(match)

        FakeTorneiraDispatcher = fudge.Fake("TorneiraDispatcher").expects("__init__")
        FakeTorneiraDispatcher.returns_fake().expects("getMapper") \
            .returns(mapper_fake) \
            .expects("getController") \
            .with_args("shouldBecontroller") \
            .returns(controller_fake)

        prepared_fake = fudge.Fake(callable=True).with_args(match).returns({'arg1':'value1'})
        write_fake = fudge.Fake(callable=True).with_args("shouldBeResponse")
        
        handler = server.TorneiraHandler(self.application_fake, self.request_fake)
        
        patches = [
            fudge.patch_object(server, "TorneiraDispatcher", FakeTorneiraDispatcher),
            fudge.patch_object(handler, "prepared_arguments", prepared_fake),
            fudge.patch_object(handler, "write", write_fake),
        ]
        

        try:
                
            handler.process_request() 

        finally:

            for p in patches:
                p.restore()
Example #49
0
    def test_can_be_get_session(self):
        settings.DATABASE_ENGINE = "shouldBeDataBase"
        settings.DATABASE_POOL_SIZE = "shouldBePoolSize"

        FakeTimerProxy = fudge.Fake("TimerProxy").expects("__init__")
        timer_proxy_instance = FakeTimerProxy.returns_fake()

        create_engine_fake = fudge.Fake(callable=True).with_args(
            "shouldBeDataBase",
            pool_size="shouldBePoolSize",
            pool_recycle=300,
            proxy=timer_proxy_instance).returns("shouldBeEngine")

        sessionmaker_fake = fudge.Fake(callable=True).with_args(
            autocommit=True,
            autoflush=False,
            expire_on_commit=False,
            bind="shouldBeEngine").returns("shouldBeScopedSession")

        scoped_session_fake = fudge.Fake(callable=True).with_args(
            "shouldBeScopedSession").returns("shouldBeSession")

        patches = [
            fudge.patch_object(meta, "TimerProxy", FakeTimerProxy),
            fudge.patch_object(meta, "create_engine", create_engine_fake),
            fudge.patch_object(meta, "sessionmaker", sessionmaker_fake),
            fudge.patch_object(meta, "scoped_session", scoped_session_fake)
        ]

        try:
            session = meta.TorneiraSession()
            self.assertEqual(session, "shouldBeSession")
        finally:

            for p in patches:
                p.restore()
    def setUp(self): 
        fudge.clear_expectations()
        MOCK_GE = (
            fudge.Fake('GameEngine')
            .expects('__init__')
            .expects('get_signal_matrix').returns(dict(fakesig=123))
            .has_attr(fighters=dict(f1='fighter1', f2='fighter2'))
            .has_attr(players=dict(p1='player1', p2='player2'))
        )

        MOCK_DD = (
            fudge.Fake('DataDriver')
            .expects('__init__')
        )

        _mock_config = (MOCK_DD.provides('get_config').returns_fake()
                        .has_attr(irc_log_channel='#log', irc_main_channel="#main"))

        MOCK_LOAD_ALL = fudge.Fake('load_all', expect_call=True)

        self.fake_dd = fudge.patch_object('urb.db', 'DataDriver', MOCK_DD)
        self.fake_ge = fudge.patch_object('urb.engine', 'GameEngine', MOCK_GE)
        self.fake_la = fudge.patch_object('urb.imports', 'load_all', MOCK_LOAD_ALL)
        fudge.clear_calls()
Example #51
0
    def inner(self):
        random_text = "Some Random Text (%d)" % random.randint(1000, 2000)
        backend = self.get_backend_stub(successful=False, reason=random_text)
        self.patches = [
            fudge.patch_object(views, "backends", backend),
        ]
        fudge.clear_calls()

        data = self.random_post_data
        response = self.client.post(self.url, data)
        backend_response = backend.get_backend().purchase()["response"]
        func(self,
             response,
             random_text=random_text,
             backend_response=backend_response)
Example #52
0
    def setUp(self):
        fudge.clear_expectations()

        # We need to mock out run, local, and put

        self.fake_run = fudge.Fake('project.run', callable=True)
        self.patched_run = fudge.patch_object(
                               project,
                               'run',
                               self.fake_run
                           )

        self.fake_local = fudge.Fake('local', callable=True)
        self.patched_local = fudge.patch_object(
                                 project,
                                 'local',
                                 self.fake_local
                             )

        self.fake_put = fudge.Fake('put', callable=True)
        self.patched_put = fudge.patch_object(
                               project,
                               'put',
                               self.fake_put
                           )

        # We don't want to create temp folders
        self.fake_mkdtemp = fudge.Fake(
                                'mkdtemp',
                                expect_call=True
                            ).returns(self.fake_tmp)
        self.patched_mkdtemp = fudge.patch_object(
                                   project,
                                   'mkdtemp',
                                   self.fake_mkdtemp
                               )
Example #53
0
 def check_connection_calls(host_strings, num_calls):
     # Clear Fudge call stack
     # Patch connect() with Fake obj set to expect num_calls calls
     patched_connect = patch_object('fabric.network', 'connect',
         Fake('connect', expect_call=True).times_called(num_calls)
     )
     try:
         # Make new cache object
         cache = HostConnectionCache()
         # Connect to all connection strings
         for host_string in host_strings:
             # Obtain connection from cache, potentially calling connect()
             cache[host_string]
     finally:
         # Restore connect()
         patched_connect.restore()
Example #54
0
 def check_connection_calls(host_strings, num_calls):
     # Clear Fudge call stack
     # Patch connect() with Fake obj set to expect num_calls calls
     patched_connect = patch_object('fabric.network', 'connect',
         Fake('connect', expect_call=True).times_called(num_calls)
     )
     try:
         # Make new cache object
         cache = HostConnectionCache()
         # Connect to all connection strings
         for host_string in host_strings:
             # Obtain connection from cache, potentially calling connect()
             cache[host_string]
     finally:
         # Restore connect()
         patched_connect.restore()
Example #55
0
def test_inherited_property():
    class SubKlass(object):
        @property
        def prop(self):
            return 'OK'
    class Klass(SubKlass):
        pass
    exact_prop = SubKlass.prop
    instance = Klass()
    fake = fudge.Fake()
    p = fudge.patch_object(instance, 'prop', fake)
    eq_(instance.prop, fake)
    p.restore()
    eq_(instance.prop, 'OK')
    assert 'prop' not in Klass.__dict__, (
                                'Klass.prop was not restored properly')
    eq_(SubKlass.prop, exact_prop)
Example #56
0
    def test_web_transport_wrong_password(self):
        fake_urlopen = fudge.Fake('urlopen')
        fake_response = fudge.Fake('fake_response')
        urllib = fudge.patch_object("urllib2", "urlopen", fake_urlopen)
        fake_urlopen.expects_call().returns(fake_response)
        fake_response.expects("read").raises(
            FakeException(
                '{"message": "error", "errors": "Bad username / password"}'))

        message = sendgrid.Message("*****@*****.**", "subject1",
                                   "plain_text", "html")
        message.add_to("*****@*****.**")

        web_transport = web.Http('username', 'password')
        self.assertRaises(sendgrid.exceptions.SGServiceException,
                          web_transport.send, message)

        urllib.restore()
Example #57
0
    def test_expunge(self):
        self.count()
        ob = PlayCount.all()[0]
        old_ts = datetime.datetime.now() - timedelta(days=8)

        @staticmethod
        def now():
            return old_ts

        # Trick the data model into saving an auto-modified timestamp
        # a week in the past.
        p = fudge.patch_object(datetime.datetime, 'now', now)
        try:
            ob.save()
        finally:
            p.restore()

        res = self.expunge()
        eq_(res.status_code, 200)
        eq_(PlayCount.all().count(1), 0)
Example #58
0
    def test_expunge(self):
        from nose.exc import SkipTest
        raise SkipTest(
                'App Engine is stupid and doesnt allow you to use a '
                'stub datetime object')
        self.count()
        ob = PlayCount.all()[0]
        old_ts = datetime.datetime.now() - timedelta(days=8)

        @staticmethod
        def now():
            return old_ts

        # Trick the data model into saving an auto-modified timestamp
        # a week in the past.
        p = fudge.patch_object(datetime.datetime, 'now', now)
        try:
            ob.save()
        finally:
            p.restore()

        res = self.expunge()
        eq_(res.status_code, 200)
        eq_(PlayCount.all().count(1), 0)
Example #59
0
 def set_date(self, datestr):
     tstamp = datetime.datetime.strptime(datestr, '%Y-%m-%d %H:%M:%S')
     fake = fudge.Fake('now', callable=True).returns(tstamp)
     if self.patch:
         self.patch.restore()
     self.patch = fudge.patch_object(datetime.datetime, 'now', fake)