예제 #1
0
def test_error(flockmock, exitmock, truncatemock, atexitmock, logmock):
    # When we attempt to acquire a lock on 'PID_FILE', the acquisition
    # fails, Log issue and exit.
    dut.PID_FILE = "test.pid"
    if (os.path.exists(dut.PID_FILE)):
        # Make sure file does not exist as a precondition
        os.remove(dut.PID_FILE)

    # Arrange error return from locking mock
    flockmock.side_effect = IOError
    exitmock.side_effect = SystemExit

    try:
        dut.prevent_duplicate(dut.PID_FILE)
    except SystemExit:
        pass  # Expected from exitmock

    # Always expect to interact with flock()
    flockmock.assert_called_once_with(match_equality(instance_of(file)),
                                      match_equality(
                                          fcntl.LOCK_EX | fcntl.LOCK_NB))

    # Assertions to prove we took the un-happy path
    exitmock.assert_called_once_with(-1)
    logmock.return_value.error.assert_called_once_with(
        match_equality(instance_of(str)))

    # The road not taken
    assert_that(truncatemock.call_count, equal_to(0))
    assert_that(atexitmock.call_count, equal_to(0))

    assert(os.path.exists(dut.PID_FILE))
    os.remove(dut.PID_FILE)
    def test_mongodb_create_user(self, call_script):
        database_base1 = factory_logical.DatabaseFactory(databaseinfra=self.databaseinfra, name="base1")

        results = [
            '  { "host": "xxx", \n"version": "2.4.6", "localTime" : ISODate("2013-09-26T20:47:56.766Z") } ',
            ' { "databases": [ { "name": "base1", "sizeOnDisk": 67108864 } ], "totalSize": 100663296 } '
        ]
        def sequence_calls(*a, **kw):
            return results.pop(0)

        call_script.side_effect = sequence_calls
        databaseinfra_status = self.driver.info()
        required_envs={
            "INSTANCE_CONNECTION": self.driver.get_connection(),
            "INSTANCE_USER": self.driver.get_user(),
            "INSTANCE_PASSWORD": self.driver.get_password(),
        }
        call_script.assert_any_call(MongoDB.SCRIPT, ["serverstatus"], envs=match_equality(has_entries(required_envs)))
        call_script.assert_any_call(MongoDB.SCRIPT, ["listdatabases"], envs=match_equality(has_entries(required_envs)))
        self.assertEquals("2.4.6", databaseinfra_status.version)
        self.assertEquals(100663296, databaseinfra_status.used_size_in_bytes)

        base1_status = databaseinfra_status.get_database_status("base1")
        self.assertEquals(database_base1, base1_status.database_model)
        self.assertEquals(67108864, base1_status.used_size_in_bytes)
예제 #3
0
def test_command_routing():
    with captured_callback() as cb:
        # UUT keeps the reference alive for CB handling
        # pylint: disable=unused-variable
        uut = RCICommandProcessor()
        cb("<test/>")

    pubmock.sendMessage.assert_called_once_with("command.test",
                element=match_equality(instance_of(ET.Element)),
                response=match_equality(instance_of(PutOnlyQueue)))
예제 #4
0
def test_command_routing():
    with captured_callback() as cb:
        # UUT keeps the reference alive for CB handling
        # pylint: disable=unused-variable
        uut = RCICommandProcessor()
        cb("<test/>")

    pubmock.sendMessage.assert_called_once_with(
        "command.test",
        element=match_equality(instance_of(ET.Element)),
        response=match_equality(instance_of(PutOnlyQueue)))
def do_send_serial(pubmock, attrs, encoded_data, transmit_data,
                   expected_addr=None):
    expected_addr = expected_addr or attrs['addr']
    pubmock.reset_mock()
    mgr = XBeeEventManager(registry)
    pollermock = mgr.poller
    pollermock.poll.return_value = [(mgr.socket.fileno.return_value,
                                     selectmock.POLLOUT)]

    # Get the listener from subscribe's last call
    listener = get_listener(pubmock)
    assert listener is not None

    # Create command object
    el = Element("send_serial", attrib=attrs)
    el.text = encoded_data

    rsp = Mock()
    listener(element=el, response=rsp)
    mgr.socket.sendto.assert_called_once_with(transmit_data,
                                (expected_addr,
                                 0xe8,
                                 0xc105,
                                 0x11,
                                 0,
                                 match_equality(instance_of(int))))

    # Grab the transmit identifier so we can complete it
    # First call, second argument, sixth member of address tuple
    tx_id = mgr.socket.sendto.call_args[0][1][5]

    rsp.put.assert_called_once_with(ResponsePending)
    rsp.reset_mock()

    # Trigger completion with transmit status
    mgr.socket.recvfrom.return_value = (
        # TX Status response, frame info, dst, and other indicators all success
        '\x8b\x00\x00\x00\x00\x00\x00',
        ('[00:00:00:00:00:00:00:00]!',
         0x0, 0xc105, 0x8b, 0x0, tx_id))

    # Tell dispatcher portion that it has data
    mgr.handle_read()

    rsp.put.assert_called_once_with(
        match_equality(instance_of(DeferredResponse)))
    # First call, only arg
    dr = rsp.put.call_args[0][0]
    print dr

    assert "error" not in dr.response.keys()
    assert dr.response.text == ""
예제 #6
0
def helper_do_successful(pubmock, attrs, text, call_setting, call_value):
    pubmock.reset_mock()
    mgr = DDOEventManager()

    pollermock = mgr.poller
    pollermock.poll.return_value = [(mgr.socket.fileno.return_value,
                                     selectmock.POLLOUT)]

    # Get the listener from subscribe's last call
    listener = get_dout_listener(pubmock)
    assert listener is not None

    el = Element("set_digital_output", attrib=attrs)
    el.text = text

    response = Mock()
    listener(element=el, response=response)

    # Check that ResponsePending was placed on the queue
    response.put.assert_called_once_with(ResponsePending)
    response.reset_mock()

    # Check the socket call was made correctly.
    addr = attrs['addr']
    normalized_addr = normalize_ieee_address(addr)

    sendto = sockmock.return_value.sendto

    payload = struct.pack('!I', call_value)

    sendto.assert_called_once_with(
        payload, (normalized_addr, call_setting, socket.XBS_OPT_DDO_APPLY,
                  match_equality(instance_of(int))))

    # Grab the transmission ID so we can present a status frame
    tx_id = sendto.call_args[0][1][3]

    sockmock.return_value.recvfrom.return_value = (
        "", ('[00:00:00:00:00:00:00:00]!', call_setting,
             socket.XBS_OPT_DDO_APPLY, tx_id, 0))

    # Tell dispatcher portion that it has data
    mgr.handle_read()

    response.put.assert_called_once_with(
        match_equality(instance_of(DeferredResponse)))
    # Extract response. First call, only arg.
    deferred_resp = response.put.call_args[0][0]

    assert "error" not in deferred_resp.response.keys()
    assert deferred_resp.response.text == ""
def do_send_serial(pubmock,
                   attrs,
                   encoded_data,
                   transmit_data,
                   expected_addr=None):
    expected_addr = expected_addr or attrs['addr']
    pubmock.reset_mock()
    mgr = XBeeEventManager(registry)
    pollermock = mgr.poller
    pollermock.poll.return_value = [(mgr.socket.fileno.return_value,
                                     selectmock.POLLOUT)]

    # Get the listener from subscribe's last call
    listener = get_listener(pubmock)
    assert listener is not None

    # Create command object
    el = Element("send_serial", attrib=attrs)
    el.text = encoded_data

    rsp = Mock()
    listener(element=el, response=rsp)
    mgr.socket.sendto.assert_called_once_with(
        transmit_data, (expected_addr, 0xe8, 0xc105, 0x11, 0,
                        match_equality(instance_of(int))))

    # Grab the transmit identifier so we can complete it
    # First call, second argument, sixth member of address tuple
    tx_id = mgr.socket.sendto.call_args[0][1][5]

    rsp.put.assert_called_once_with(ResponsePending)
    rsp.reset_mock()

    # Trigger completion with transmit status
    mgr.socket.recvfrom.return_value = (
        # TX Status response, frame info, dst, and other indicators all success
        '\x8b\x00\x00\x00\x00\x00\x00',
        ('[00:00:00:00:00:00:00:00]!', 0x0, 0xc105, 0x8b, 0x0, tx_id))

    # Tell dispatcher portion that it has data
    mgr.handle_read()

    rsp.put.assert_called_once_with(
        match_equality(instance_of(DeferredResponse)))
    # First call, only arg
    dr = rsp.put.call_args[0][0]
    print dr

    assert "error" not in dr.response.keys()
    assert dr.response.text == ""
 def test_mongodb_remove_database(self, call_script):
     self.driver.remove_database(self.database)
     required_envs={
         "INSTANCE_CONNECTION": self.driver.get_connection(),
         "INSTANCE_USER": self.driver.get_user(),
         "INSTANCE_PASSWORD": self.driver.get_password(),
         "DATABASE_NAME": self.database.name,
     }
     call_script.assert_called_once_with(MongoDB.SCRIPT, ['dropdatabase'], envs=match_equality(has_entries(required_envs)))
 def test_check_status_will_raises_authentication_error(self, call_script):
     def raise_error(*a, **kw):
         raise ErrorRunningScript(script_name=MongoDB.SCRIPT, exit_code=1, stdout="Error: 18 { code: 18, ok: 0.0, errmsg: \"auth fails\" }")
     call_script.side_effect = raise_error
     self.assertRaises(AuthenticationError, self.driver.check_status)
     required_envs={
         "INSTANCE_CONNECTION": self.driver.get_connection(),
         "INSTANCE_USER": self.driver.get_user(),
         "INSTANCE_PASSWORD": self.driver.get_password(),
     }
     call_script.assert_called_once_with(MongoDB.SCRIPT, ["status"], envs=match_equality(has_entries(required_envs)))
 def test_mongodb_create_user(self, call_script):
     self.driver.create_user(self.credential)
     required_envs={
         "INSTANCE_CONNECTION": self.driver.get_connection(),
         "INSTANCE_USER": self.driver.get_user(),
         "INSTANCE_PASSWORD": self.driver.get_password(),
         "DATABASE_NAME": self.database.name,
         "CREDENTIAL_USER": self.credential.user,
         "CREDENTIAL_PASSWORD": self.credential.password,
     }
     call_script.assert_called_once_with(MongoDB.SCRIPT, ['adduser'], envs=match_equality(has_entries(required_envs)))
 def test_check_status_will_raises_connection_error(self, call_script):
     def raise_error(*a, **kw):
         raise ErrorRunningScript(script_name=MongoDB.SCRIPT, exit_code=1, stdout="Error: couldn't connect to server xxx:yyy at src/mongo/shell/mongo.js:147")
     call_script.side_effect = raise_error
     self.assertRaises(ConnectionError, self.driver.check_status)
     required_envs={
         "INSTANCE_CONNECTION": self.driver.get_connection(),
         "INSTANCE_USER": self.driver.get_user(),
         "INSTANCE_PASSWORD": self.driver.get_password(),
     }
     call_script.assert_called_once_with(MongoDB.SCRIPT, ["status"], envs=match_equality(has_entries(required_envs)))
예제 #12
0
def test_success(flockmock, exitmock, truncatemock, atexitmock, logmock):
    # When we attempt to acquire a lock on 'PID_FILE', the acquisition
    # suceeds, file is created, and we arrange for it to be
    # removed.

    dut.PID_FILE = "test.pid"
    if (os.path.exists(dut.PID_FILE)):
        # Make sure file does not exist as a precondition
        os.remove(dut.PID_FILE)

    dut.prevent_duplicate(dut.PID_FILE)

    # Always expect to interact with flock()
    flockmock.assert_called_once_with(match_equality(instance_of(file)),
                                      match_equality(
                                          fcntl.LOCK_EX | fcntl.LOCK_NB))

    # The road not taken
    assert_that(exitmock.call_count, equal_to(0))
    assert_that(logmock.return_value.error.call_count, equal_to(0))

    # Assertions to prove we took the happy path
    truncatemock.assert_called_once_with(
        match_equality(instance_of(int)),
        match_equality(0))
    atexitmock.assert_called_once_with(
        match_equality(dut.cleanup_pidfile),
        match_equality(instance_of(file)))

    assert(os.path.exists(dut.PID_FILE))

    # Clean up
    os.remove(dut.PID_FILE)
예제 #13
0
def test_multiple_commands():

    with captured_callback() as cb:
        # UUT keeps the reference alive for CB handling
        # pylint: disable=unused-variable
        uut = RCICommandProcessor()
        cb("<test1/><test2/><test3/><test4/>")

    calls = [
        call("command.test1",
            element=match_equality(instance_of(ET.Element)),
             response=match_equality(instance_of(PutOnlyQueue))),
        call("command.test2",
            element=match_equality(instance_of(ET.Element)),
             response=match_equality(instance_of(PutOnlyQueue))),
        call("command.test3",
            element=match_equality(instance_of(ET.Element)),
             response=match_equality(instance_of(PutOnlyQueue))),
        call("command.test4",
            element=match_equality(instance_of(ET.Element)),
             response=match_equality(instance_of(PutOnlyQueue))),
    ]

    pubmock.sendMessage.assert_has_calls(calls)
예제 #14
0
def test_multiple_commands():

    with captured_callback() as cb:
        # UUT keeps the reference alive for CB handling
        # pylint: disable=unused-variable
        uut = RCICommandProcessor()
        cb("<test1/><test2/><test3/><test4/>")

    calls = [
        call("command.test1",
             element=match_equality(instance_of(ET.Element)),
             response=match_equality(instance_of(PutOnlyQueue))),
        call("command.test2",
             element=match_equality(instance_of(ET.Element)),
             response=match_equality(instance_of(PutOnlyQueue))),
        call("command.test3",
             element=match_equality(instance_of(ET.Element)),
             response=match_equality(instance_of(PutOnlyQueue))),
        call("command.test4",
             element=match_equality(instance_of(ET.Element)),
             response=match_equality(instance_of(PutOnlyQueue))),
    ]

    pubmock.sendMessage.assert_has_calls(calls)
예제 #15
0
 def testMatcherStringIsMatcherDescription(self):
     matcher = equal_to("bar")
     assert str(match_equality(matcher)) == tostring(matcher)
예제 #16
0
 def testMatcherIsNotEqualWhenMatchesIsFalse(self):
     matcher = equal_to("bar")
     assert match_equality(matcher) != "foo"
예제 #17
0
 def testMatcherIsEqualWhenMatchesIsTrue(self):
     matcher = equal_to("bar")
     assert match_equality(matcher) == "bar"
예제 #18
0
 def testMatchesWhenProvidedAnObject(self):
     assert match_equality('bar') == 'bar'
예제 #19
0
 def testMatcherReprIsMatcher(self):
     matcher = equal_to('bar')
     assert repr(match_equality(matcher)) == tostring(matcher)
예제 #20
0
 def testMatcherStringIsMatcherDescription(self):
     matcher = equal_to('bar')
     assert str(match_equality(matcher)) == tostring(matcher)
예제 #21
0
 def testMatcherIsNotEqualWhenMatchesIsFalse(self):
     matcher = equal_to('bar')
     assert match_equality(matcher) != 'foo'
예제 #22
0
 def testMatcherIsEqualWhenMatchesIsTrue(self):
     matcher = equal_to('bar')
     assert match_equality(matcher) == 'bar'
def do_send_serial_error(pubmock, attrs, data, error_prefix, error_hint=None,
                         tx_status_err=0, send_exc=None, fileno_val=0):
    pubmock.reset_mock()
    mgr = XBeeEventManager(registry)
    pollermock = mgr.poller

    if fileno_val:
        fno_return = fileno_val
    else:
        fno_return = mgr.socket.fileno.return_value

    pollermock.poll.return_value = [(fno_return,
                                     selectmock.POLLOUT)]

    # Get the listener from subscribe's last call
    listener = get_listener(pubmock)
    assert listener is not None

    # Create command object
    el = Element("send_serial", attrib=attrs)
    el.text = data

    if send_exc:
        mgr.socket.sendto.side_effect = send_exc

    rsp = Mock()
    listener(element=el, response=rsp)

    if send_exc:
        mgr.socket.sendto.side_effect = None

    if not tx_status_err:
        assert_that(rsp.put.call_count, equal_to(1))
        r = rsp.put.call_args[0][0]
        rsp.put.assert_called_once_with(match_equality(instance_of(Element)))
        # Only call, only arg is hopeful error element
        el = rsp.put.call_args[0][0]
        assert_command_error(el, error_prefix, error_hint)

        return

    #### Deal only with tx_status errors beyond here

    # Grab the transmit identifier so we can comlete it
    # First call, second argument, sixth member of address tuple
    tx_id = mgr.socket.sendto.call_args[0][1][5]

    rsp.put.assert_called_once_with(ResponsePending)
    rsp.reset_mock()

    # Trigger completion with transmit status
    mgr.socket.recvfrom.return_value = (
        # TX Status response, frame info, dst, and other
        # indicators all success
        '\x8b\x00\x00\x00\x00' + chr(tx_status_err) + '\x00',
        ('[00:00:00:00:00:00:00:00]!',
         0x0, 0xc105, 0x8b, 0x0, tx_id))

    print mgr.socket.recvfrom.return_value

    # Tell dispatcher portion that it has data
    mgr.handle_read()

    rsp.put.assert_called_once_with(
        match_equality(instance_of(DeferredResponse)))
    # First call, only arg
    dr = rsp.put.call_args[0][0]
    el = dr.response
    assert_command_error(el, error_prefix, error_hint)
예제 #24
0
 def testMatcherReprIsMatcher(self):
     matcher = equal_to("bar")
     assert repr(match_equality(matcher)) == tostring(matcher)
def is_timestamp():
    return match_equality(matches_regexp(TIMESTAMP_PATTERN))
예제 #26
0
 def testMatchesWhenProvidedAnObject(self):
     assert match_equality("bar") == "bar"
def do_send_serial_error(pubmock,
                         attrs,
                         data,
                         error_prefix,
                         error_hint=None,
                         tx_status_err=0,
                         send_exc=None,
                         fileno_val=0):
    pubmock.reset_mock()
    mgr = XBeeEventManager(registry)
    pollermock = mgr.poller

    if fileno_val:
        fno_return = fileno_val
    else:
        fno_return = mgr.socket.fileno.return_value

    pollermock.poll.return_value = [(fno_return, selectmock.POLLOUT)]

    # Get the listener from subscribe's last call
    listener = get_listener(pubmock)
    assert listener is not None

    # Create command object
    el = Element("send_serial", attrib=attrs)
    el.text = data

    if send_exc:
        mgr.socket.sendto.side_effect = send_exc

    rsp = Mock()
    listener(element=el, response=rsp)

    if send_exc:
        mgr.socket.sendto.side_effect = None

    if not tx_status_err:
        assert_that(rsp.put.call_count, equal_to(1))
        r = rsp.put.call_args[0][0]
        rsp.put.assert_called_once_with(match_equality(instance_of(Element)))
        # Only call, only arg is hopeful error element
        el = rsp.put.call_args[0][0]
        assert_command_error(el, error_prefix, error_hint)

        return

    #### Deal only with tx_status errors beyond here

    # Grab the transmit identifier so we can comlete it
    # First call, second argument, sixth member of address tuple
    tx_id = mgr.socket.sendto.call_args[0][1][5]

    rsp.put.assert_called_once_with(ResponsePending)
    rsp.reset_mock()

    # Trigger completion with transmit status
    mgr.socket.recvfrom.return_value = (
        # TX Status response, frame info, dst, and other
        # indicators all success
        '\x8b\x00\x00\x00\x00' + chr(tx_status_err) + '\x00',
        ('[00:00:00:00:00:00:00:00]!', 0x0, 0xc105, 0x8b, 0x0, tx_id))

    print mgr.socket.recvfrom.return_value

    # Tell dispatcher portion that it has data
    mgr.handle_read()

    rsp.put.assert_called_once_with(
        match_equality(instance_of(DeferredResponse)))
    # First call, only arg
    dr = rsp.put.call_args[0][0]
    el = dr.response
    assert_command_error(el, error_prefix, error_hint)