Example #1
0
    def test_recover_retry_txn(self):
        txn = Mock()
        txns = [txn, None]
        pop_txn = False

        def take_txn(*args, **kwargs):
            if pop_txn:
                return defer.succeed(txns.pop(0))
            else:
                return defer.succeed(txn)

        self.store.get_oldest_unsent_txn = Mock(side_effect=take_txn)

        self.recoverer.recover()
        self.assertEquals(0, self.store.get_oldest_unsent_txn.call_count)
        txn.send = Mock(return_value=False)
        self.clock.advance_time(2)
        self.assertEquals(1, txn.send.call_count)
        self.assertEquals(0, txn.complete.call_count)
        self.assertEquals(0, self.callback.call_count)
        self.clock.advance_time(4)
        self.assertEquals(2, txn.send.call_count)
        self.assertEquals(0, txn.complete.call_count)
        self.assertEquals(0, self.callback.call_count)
        self.clock.advance_time(8)
        self.assertEquals(3, txn.send.call_count)
        self.assertEquals(0, txn.complete.call_count)
        self.assertEquals(0, self.callback.call_count)
        txn.send = Mock(return_value=True)  # successfully send the txn
        pop_txn = True  # returns the txn the first time, then no more.
        self.clock.advance_time(16)
        self.assertEquals(1, txn.send.call_count)  # new mock reset call count
        self.assertEquals(1, txn.complete.call_count)
        self.callback.assert_called_once_with(self.recoverer)
    def setUp(self):
        job_mock = Mock()
        job_mock.update = Mock()
        self.job = job_mock

        notification_mock = Mock()
        notification_mock.send = Mock()

        notification_fail = Mock()
        notification_fail.send = Mock(side_effect=Exception("something went wrong!"))

        self.success_notification = notification_mock
        self.failure_notification = notification_fail
Example #3
0
    def test_single_service_up_txn_not_sent(self):
        # Test: The AS is up and the txn is not sent. A Recoverer is made and
        # started.
        service = Mock()
        events = [Mock(), Mock()]
        txn_id = "foobar"
        txn = Mock(id=txn_id, service=service, events=events)

        # mock methods
        self.store.get_appservice_state = Mock(return_value=defer.succeed(ApplicationServiceState.UP))
        self.store.set_appservice_state = Mock(return_value=defer.succeed(True))
        txn.send = Mock(return_value=defer.succeed(False))  # fails to send
        self.store.create_appservice_txn = Mock(return_value=defer.succeed(txn))

        # actual call
        self.txnctrl.send(service, events)

        self.store.create_appservice_txn.assert_called_once_with(service=service, events=events)
        self.assertEquals(1, self.recoverer_fn.call_count)  # recoverer made
        self.assertEquals(1, self.recoverer.recover.call_count)  # and invoked
        self.assertEquals(1, len(self.txnctrl.recoverers))  # and stored
        self.assertEquals(0, txn.complete.call_count)  # txn not completed
        self.store.set_appservice_state.assert_called_once_with(
            service, ApplicationServiceState.DOWN  # service marked as down
        )
Example #4
0
    def test_registration_craps_out(self):
        from horus.views                import RegisterController
        from pyramid_mailer.interfaces  import IMailer
        from horus.interfaces           import IUserClass
        from horus.tests.models         import User
        from horus.interfaces   import IActivationClass
        from horus.tests.models import Activation
        self.config.registry.registerUtility(Activation, IActivationClass)

        self.config.registry.registerUtility(User, IUserClass)

        def send(message):
            raise Exception("I broke!")

        mailer = Mock()
        mailer.send = send

        self.config.include('horus')
        self.config.registry.registerUtility(mailer, IMailer)

        self.config.add_route('index', '/')

        request = self.get_csrf_request(post={
            'username': 'admin',
            'password': {
                'password': 'test123',
                'password-confirm': 'test123',
            },
            'email': 'sontek@gmail.com'
        }, request_method='POST')

        request.user = Mock()
        controller = RegisterController(request)

        self.assertRaises(Exception, controller.register)
Example #5
0
    def test_quit_bot(self):
        from functions import quit_bot

        with nested(
            patch("functions.log_write"), patch("sys.stdout", new=StringIO()), patch("functions.get_datetime")
        ) as (log_write, stdout, get_dt):
            get_dt.return_value = {"date": "42", "time": "42"}

            s = Mock()
            s.send.side_effect = IOError()

            message = "Unexpected error while quitting: \n"

            self.assertFalse(quit_bot(s, "foo"))
            self.assertEqual(stdout.getvalue(), message)

            log_write.assert_called_with("foo", "42", " <> ", message)

            s.send.side_effect = None
            s.send = Mock()

            self.assertTrue(quit_bot(s, "foo"))

            log_write.assert_called_with("foo", "42", " <> ", "QUIT\r\n")
            s.send.assert_called_with("QUIT\r\n")
Example #6
0
    def test_registration_craps_out(self):
        from pyramid_signup.views import RegisterController
        from pyramid_mailer.interfaces import IMailer

        def send(message):
            raise Exception("I broke!")

        mailer = Mock()
        mailer.send = send

        self.config.include("pyramid_signup")
        self.config.registry.registerUtility(mailer, IMailer)

        self.config.add_route("index", "/")

        request = self.get_csrf_request(
            post={
                "Username": "admin",
                "Password": {"value": "test123", "confirm": "test123"},
                "Email": "sontek@gmail.com",
            },
            request_method="POST",
        )

        flash = Mock()
        request.session.flash = flash

        request.user = Mock()
        controller = RegisterController(request)
        controller.register()

        flash.assert_called_with("I broke!", "error")
    def test_source_process(self):
        source = FilesystemObserverSource("*.txt", "/some/directory")

        reactor = Mock()
        reactor.spawnProcess = Mock(spec=_spawnProcess)

        scheduler = Mock()
        scheduler.send = Mock(spec=Scheduler.send)

        # Attach source to the scheduler.
        yield source.attach(scheduler, reactor)
        self.assertEquals(reactor.spawnProcess.call_count, 1)

        # Simulate a message directed to the source.
        msg = {
            "port": "default",
            "item": {
                "type": "delta",
                "date": datetime(2010, 10, 20, 20, 10),
                "inserts": ["abcdefg"],
                "deletes": ["hiklmno"],
                "data": {"abcdefg": {"path": "/some/directory/xyz.txt"}},
            },
        }

        matches = MatchesSendDeltaItemInvocation(copy.deepcopy(msg["item"]), source)
        source.peer.dataReceived(BSON.encode(msg))
        self.assertEquals(scheduler.send.call_count, 1)
        self.assertThat(scheduler.send.call_args, matches)
Example #8
0
 def setUp(self):
     socket = Mock()
     socket.recv = Mock()
     socket.send = Mock()
     with patch("socket.create_connection") as create_connection:
         create_connection.return_value = socket
         self.connection = TCPSocketConnection(("localhost", 1234))
Example #9
0
    def test_join_channels(self):
        from functions import join_channels

        with nested(
            patch("functions.log_write"), patch("sys.stdout", new=StringIO()), patch("functions.get_datetime")
        ) as (log_write, stdout, get_dt):
            get_dt.return_value = {"date": "42", "time": "42"}

            s = Mock()
            s.send.side_effect = IOError()

            channels = ["#foo", "#bar"]
            clist = ",".join(channels)

            message = "Unexpected error while joining {0}: {1}".format(clist, "\n")

            self.assertFalse(join_channels(channels, s, "foo"))
            self.assertEqual(stdout.getvalue(), message)

            log_write.assert_called_with("foo", "42", " <> ", message)

            log_write.call_args_list = []
            s.send.side_effect = None
            s.send = Mock()
            msg = "Joined: {0}\n".format(clist)

            self.assertTrue(join_channels(channels, s, "foo"))

            log_write.assert_called_with("foo", "42", " <> ", msg)
            self.assertEqual(stdout.getvalue(), message + msg)

            s.send.assert_called_with("JOIN " + clist + "\r\n")
Example #10
0
    def test_name_bot(self):
        from functions import name_bot

        logfile = "foo"
        irc = Mock()
        irc.send = Mock()

        nicks = ["nick1", "nick2"]

        with nested(
            patch("functions.get_nick"),
            patch("functions.log_write"),
            patch("functions.get_datetime"),
            patch("config.real_name", new="foo"),
            patch("random.sample"),
        ) as (get_nick, log_write, get_dt, real_name, sample):
            get_dt.return_value = {"date": "42", "time": "42"}
            get_nick.return_value = iter(nicks)
            sample.return_value = "baz"

            irc.recv.side_effect = ["foo", "Nickname is already in use", nicks[1]]

            self.assertEqual(name_bot(irc, nicks, real_name, logfile), nicks[1])
            expected_log_write_calls = [
                call(logfile, "42", " <> ", "Set nick to: {0}\n".format(nicks[0])),
                call(logfile, "42", " <> ", "Changing nick to: {0}\n".format(nicks[1])),
            ]

            expected_send_calls = [
                call("NICK " + nicks[0] + "\r\n"),
                call("USER {0} {0} {0} :{1}\r\n".format(nicks[0], real_name)),
                call("NICK " + nicks[1] + "\r\n"),
            ]

            self.assertListEqual(expected_log_write_calls, log_write.call_args_list)

            self.assertListEqual(expected_send_calls, irc.send.call_args_list)

            nicks = ["used_nick"]
            get_nick.return_value = iter(nicks)
            irc.recv.side_effect = ["Nickname is already in use", "motd"]

            self.assertEqual(name_bot(irc, nicks, real_name, logfile), nicks[0] + "baz")
            expected_log_write_calls = [
                call(logfile, "42", " <> ", "Set nick to: {0}\n".format(nicks[0])),
                call(logfile, "42", " <> ", "Changing nick to: {0}\n".format(nicks[0] + "baz")),
            ]

            expected_send_calls = [
                call("NICK " + nicks[0] + "\r\n"),
                call("USER {0} {0} {0} :{1}\r\n".format(nicks[0], real_name)),
                call("NICK " + nicks[0] + "baz\r\n"),
            ]
    def test_handle_response_401(self):
        # Get a 401 from server, authenticate, and get a 200 back.
        with patch.multiple(
            kerberos_module_name,
            authGSSClientInit=clientInit_complete,
            authGSSClientResponse=clientResponse,
            authGSSClientStep=clientStep_continue,
        ):

            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {"www-authenticate": "negotiate servertoken"}

            connection = Mock()
            connection.send = Mock(return_value=response_ok)

            raw = Mock()
            raw.release_conn = Mock(return_value=None)

            request = requests.Request()
            response = requests.Response()
            response.request = request
            response.url = "http://www.example.org/"
            response.headers = {"www-authenticate": "negotiate token"}
            response.status_code = 401
            response.connection = connection
            response._content = ""
            response.raw = raw

            auth = requests_kerberos.HTTPKerberosAuth()
            auth.handle_other = Mock(return_value=response_ok)

            r = auth.handle_response(response)

            self.assertTrue(response in r.history)
            auth.handle_other.assert_called_once_with(response_ok)
            self.assertEqual(r, response_ok)
            self.assertEqual(request.headers["Authorization"], "Negotiate GSSRESPONSE")
            connection.send.assert_called_with(request)
            raw.release_conn.assert_called_with()
            clientInit_complete.assert_called_with(
                "HTTP@www.example.org",
                gssflags=(kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG),
                principal=None,
            )
            clientStep_continue.assert_called_with("CTX", "token")
            clientResponse.assert_called_with("CTX")
Example #12
0
    def test_single_service_up_txn_sent(self):
        # Test: The AS is up and the txn is successfully sent.
        service = Mock()
        events = [Mock(), Mock()]
        txn_id = "foobar"
        txn = Mock(id=txn_id, service=service, events=events)

        # mock methods
        self.store.get_appservice_state = Mock(return_value=defer.succeed(ApplicationServiceState.UP))
        txn.send = Mock(return_value=defer.succeed(True))
        self.store.create_appservice_txn = Mock(return_value=defer.succeed(txn))

        # actual call
        self.txnctrl.send(service, events)

        self.store.create_appservice_txn.assert_called_once_with(service=service, events=events)  # txn made and saved
        self.assertEquals(0, len(self.txnctrl.recoverers))  # no recoverer made
        txn.complete.assert_called_once_with(self.store)  # txn completed
    def test_handle_response_401(self):
        with patch.multiple(
            "kerberos",
            authGSSClientInit=clientInit_complete,
            authGSSClientResponse=clientResponse,
            authGSSClientStep=clientStep_continue,
        ):

            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {"www-authenticate": "negotiate servertoken"}

            connection = Mock()
            connection.send = Mock(return_value=response_ok)

            raw = Mock()
            raw.release_conn = Mock(return_value=None)

            request = requests.Request()
            response = requests.Response()
            response.request = request
            response.url = "http://www.example.org/"
            response.headers = {"www-authenticate": "negotiate token"}
            response.status_code = 401
            response.connection = connection
            response._content = ""
            response.raw = raw

            auth = requests_gssapi.HTTPGSSAPIAuth()
            auth.handle_other = Mock(return_value=response_ok)

            r = auth.handle_response(response)

            self.assertTrue(response in r.history)
            auth.handle_other.assert_called_with(response_ok)
            self.assertEqual(r, response_ok)
            self.assertEqual(request.headers["Authorization"], "Negotiate GSSRESPONSE")
            connection.send.assert_called_with(request)
            raw.release_conn.assert_called_with()
            clientInit_complete.assert_called_with("HTTP@www.example.org")
            clientStep_continue.assert_called_with("CTX", "token")
            clientResponse.assert_called_with("CTX")
    def test_delegation(self):
        with patch.multiple(
            "kerberos",
            authGSSClientInit=clientInit_complete,
            authGSSClientResponse=clientResponse,
            authGSSClientStep=clientStep_continue,
        ):

            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {"www-authenticate": "negotiate servertoken"}

            connection = Mock()
            connection.send = Mock(return_value=response_ok)

            raw = Mock()
            raw.release_conn = Mock(return_value=None)

            request = requests.Request()
            response = requests.Response()
            response.request = request
            response.url = "http://www.example.org/"
            response.headers = {"www-authenticate": "negotiate token"}
            response.status_code = 401
            response.connection = connection
            response._content = ""
            response.raw = raw
            auth = requests_kerberos.HTTPKerberosAuth(1, "HTTP", True)
            r = auth.authenticate_user(response)

            self.assertTrue(response in r.history)
            self.assertEqual(r, response_ok)
            self.assertEqual(request.headers["Authorization"], "Negotiate GSSRESPONSE")
            connection.send.assert_called_with(request)
            raw.release_conn.assert_called_with()
            clientInit_complete.assert_called_with(
                "HTTP@www.example.org",
                gssflags=(kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG | kerberos.GSS_C_DELEG_FLAG),
            )
            clientStep_continue.assert_called_with("CTX", "token")
            clientResponse.assert_called_with("CTX")
Example #15
0
    def test_partial_send(self):
        mock_sock = Mock()
        mock_sock.send = Mock(return_value=3)

        string1 = "abcdefghi"
        w = SocketReaderWriter(mock_sock)
        w.tx_bytes(string1)

        w.write_event()
        assert mock_sock.send.called_with(string1)

        w.write_event()
        assert mock_sock.send.called_with(string1[3:])

        w.write_event()
        assert mock_sock.send.called_with(string1[6:])

        call_count = mock_sock.send.call_count
        w.write_event()
        assert mock_sock.send.call_count == call_count
Example #16
0
    def testGetTimeShouldReturnKeyAndTime(self):
        # setup
        expected_key = "678652045157661214"
        expected_time = 1353868293322
        request_string = {
            "cmd": "TIME",
            "key": expected_key,
            "redirect": "http://95.163.80.23/zombievk",
            "id": "45",
            "time": expected_time,
        }
        request_string = request_string
        request_sender = Mock()
        request_sender.send = Mock(return_value=dict2obj(request_string))
        game_initializer = GameInitializer(Mock(), request_sender, Mock(), Mock(), Mock())

        # exercise
        actual_key, actual_time = game_initializer.get_time()
        # verify
        self.assertEqual(expected_time, actual_time)
        self.assertEqual(expected_key, actual_key)
Example #17
0
    def test_is_registered(self):
        from functions import is_registered

        checked_nick = "foobaz"
        s = Mock()

        s.send = Mock()
        s.recv.return_value = "NickServ Last seen  : now"

        self.assertTrue(is_registered(s, checked_nick))

        s.recv.return_value = "NickServ"
        self.assertFalse(is_registered(s, checked_nick))

        response = ["baz", "NickServ Information on:", "NickServ", "foo"]
        # side_effect will return the next item from the list which will be
        # assigned to is_registered.receive this way I'm able to test the
        # pass branch in the function
        s.recv.side_effect = response

        self.assertFalse(is_registered(s, checked_nick))
Example #18
0
    def test_recover_single_txn(self):
        txn = Mock()
        # return one txn to send, then no more old txns
        txns = [txn, None]

        def take_txn(*args, **kwargs):
            return defer.succeed(txns.pop(0))

        self.store.get_oldest_unsent_txn = Mock(side_effect=take_txn)

        self.recoverer.recover()
        # shouldn't have called anything prior to waiting for exp backoff
        self.assertEquals(0, self.store.get_oldest_unsent_txn.call_count)
        txn.send = Mock(return_value=True)
        # wait for exp backoff
        self.clock.advance_time(2)
        self.assertEquals(1, txn.send.call_count)
        self.assertEquals(1, txn.complete.call_count)
        # 2 because it needs to get None to know there are no more txns
        self.assertEquals(2, self.store.get_oldest_unsent_txn.call_count)
        self.callback.assert_called_once_with(self.recoverer)
        self.assertEquals(self.recoverer.service, self.service)
Example #19
0
    def test_registration_craps_out(self):
        from horus.views import RegisterController
        from pyramid_mailer.interfaces import IMailer
        from horus.interfaces import IUserClass
        from horus.tests.models import User
        from horus.interfaces import IActivationClass
        from horus.tests.models import Activation

        self.config.registry.registerUtility(Activation, IActivationClass)

        self.config.registry.registerUtility(User, IUserClass)

        def send(message):
            raise Exception("I broke!")

        mailer = Mock()
        mailer.send = send

        self.config.include("horus")
        self.config.registry.registerUtility(mailer, IMailer)

        self.config.add_route("index", "/")

        request = self.get_csrf_request(
            post={
                "username": "admin",
                "password": {"password": "test123", "password-confirm": "test123"},
                "email": "sontek@gmail.com",
            },
            request_method="POST",
        )

        flash = Mock()
        request.session.flash = flash

        request.user = Mock()
        controller = RegisterController(request)

        self.assertRaises(Exception, controller.register)