Example #1
0
    def test_channel_pool(self):
        ncm = Mock()
        ncm.return_value = Mock(spec=BidirClientChannel)
        ncm.return_value._queue_auto_delete = False
        ncm.return_value.get_channel_id.return_value = sentinel.chid

        with patch("pyon.net.messaging.NodeB._new_channel", ncm):
            ch = self._node.channel(BidirClientChannel)

            # should expect to see this show up in the node's mappings
            self.assertIn(ch, self._node._bidir_pool.itervalues())
            self.assertIn(sentinel.chid, self._node._pool_map)
            self.assertEquals(len(self._node._pool_map), 1)
            self.assertEquals(len(self._node._pool_map), len(self._node._bidir_pool))

        # let's grab another one to watch our pool grow
        # return value is not a mock factory - it returns the same mock instance as we declared above
        # so redeclare it so they get unique chids
        ncm.return_value = Mock(spec=BidirClientChannel)
        ncm.return_value._queue_auto_delete = False
        ncm.return_value.get_channel_id.return_value = sentinel.chid2

        with patch("pyon.net.messaging.NodeB._new_channel", ncm):
            ch2 = self._node.channel(BidirClientChannel)

        self.assertEquals(ch.get_channel_id(), sentinel.chid)
        self.assertEquals(ch2.get_channel_id(), sentinel.chid2)
        self.assertNotEqual(ch, ch2)
        self.assertIn(ch2, self._node._bidir_pool.itervalues())
        self.assertIn(sentinel.chid2, self._node._pool_map)
        self.assertEquals(len(self._node._pool_map), 2)
        self.assertEquals(len(self._node._pool_map), len(self._node._bidir_pool))
Example #2
0
 def test_init_sts(self):
     mock_svc1 = Mock(spec_set=_AwsService)
     mock_svc2 = Mock(spec_set=_AwsService)
     mock_foo = Mock(spec_set=_AwsService)
     mock_bar = Mock(spec_set=_AwsService)
     mock_ta = Mock(spec_set=TrustedAdvisor)
     mock_foo.return_value = mock_svc1
     mock_bar.return_value = mock_svc2
     svcs = {"SvcFoo": mock_foo, "SvcBar": mock_bar}
     with patch.dict("awslimitchecker.checker._services", values=svcs, clear=True):
         with patch.multiple(
             "awslimitchecker.checker",
             logger=DEFAULT,
             _get_version_info=DEFAULT,
             TrustedAdvisor=DEFAULT,
             autospec=True,
         ) as mocks:
             mock_version = mocks["_get_version_info"]
             mock_version.return_value = self.mock_ver_info
             mock_ta_constr = mocks["TrustedAdvisor"]
             mocks["TrustedAdvisor"].return_value = mock_ta
             cls = AwsLimitChecker(account_id="123456789012", account_role="myrole", region="myregion")
     # dict should be of _AwsService instances
     assert cls.services == {"SvcFoo": mock_svc1, "SvcBar": mock_svc2}
     # _AwsService instances should exist, but have no other calls
     assert mock_foo.mock_calls == [call(80, 99, "123456789012", "myrole", "myregion", None)]
     assert mock_bar.mock_calls == [call(80, 99, "123456789012", "myrole", "myregion", None)]
     assert mock_ta_constr.mock_calls == [
         call(account_id="123456789012", account_role="myrole", region="myregion", external_id=None)
     ]
     assert mock_svc1.mock_calls == []
     assert mock_svc2.mock_calls == []
     assert self.mock_version.mock_calls == [call()]
     assert self.cls.vinfo == self.mock_ver_info
Example #3
0
    def test_handles(self, mock_get_regex):
        match = Mock()
        mock_get_regex.return_value = Mock()
        mock_get_regex.return_value.match = match

        evt = Mock()
        evt.filename = "event.txt"

        if self.test_obj.__basenames__:
            match.return_value = False
            self.assertFalse(self.test_obj.handles(evt))
            mock_get_regex.assert_called_with([b for b in self.test_obj.__basenames__])
            print("match calls: %s" % match.call_args_list)
            print("expected: %s" % [call(evt.filename) for b in self.test_obj.__basenames__])
            match.assert_called_with(evt.filename)

            mock_get_regex.reset_mock()
            match.reset_mock()
            match.return_value = True
            self.assertTrue(self.test_obj.handles(evt))
            match.assert_called_with(evt.filename)
        else:
            match.return_value = False
            self.assertFalse(self.test_obj.handles(evt, basename=os.path.basename(self.path)))
            mock_get_regex.assert_called_with([os.path.basename(self.path)])
            match.assert_called_with(evt.filename)

            mock_get_regex.reset_mock()
            match.reset_mock()
            match.return_value = True
            self.assertTrue(self.test_obj.handles(evt, basename=os.path.basename(self.path)))
            mock_get_regex.assert_called_with([os.path.basename(self.path)])
            match.assert_called_with(evt.filename)
Example #4
0
    def test_canInstall(self, mock_canInstall):
        posix = self.get_obj()
        entry = lxml.etree.Element("Path", name="test", type="file")

        # first, test superclass canInstall failure
        mock_canInstall.return_value = False
        self.assertFalse(posix.canInstall(entry))
        mock_canInstall.assert_called_with(posix, entry)

        # next, test fully_specified failure
        posix.logger.error.reset_mock()
        mock_canInstall.reset_mock()
        mock_canInstall.return_value = True
        mock_fully_spec = Mock()
        mock_fully_spec.return_value = False
        posix._handlers[entry.get("type")].fully_specified = mock_fully_spec
        self.assertFalse(posix.canInstall(entry))
        mock_canInstall.assert_called_with(posix, entry)
        mock_fully_spec.assert_called_with(entry)
        self.assertTrue(posix.logger.error.called)

        # finally, test success
        posix.logger.error.reset_mock()
        mock_canInstall.reset_mock()
        mock_fully_spec.reset_mock()
        mock_fully_spec.return_value = True
        self.assertTrue(posix.canInstall(entry))
        mock_canInstall.assert_called_with(posix, entry)
        mock_fully_spec.assert_called_with(entry)
        self.assertFalse(posix.logger.error.called)
Example #5
0
    def test_channel_pool_release(self):
        ncm = Mock()
        ncm.return_value = Mock(spec=BidirClientChannel)
        ncm.return_value._queue_auto_delete = False
        ncm.return_value.get_channel_id.return_value = sentinel.chid

        with patch("pyon.net.messaging.NodeB._new_channel", ncm):
            ch = self._node.channel(BidirClientChannel)

        # return value is not a mock factory - it returns the same mock instance as we declared above
        # so redeclare it so they get unique chids
        ncm.return_value = Mock(spec=BidirClientChannel)
        ncm.return_value._queue_auto_delete = False
        ncm.return_value.get_channel_id.return_value = sentinel.chid2
        with patch("pyon.net.messaging.NodeB._new_channel", ncm):
            ch2 = self._node.channel(BidirClientChannel)

        self.assertEquals(ch.get_channel_id(), sentinel.chid)
        self.assertEquals(ch2.get_channel_id(), sentinel.chid2)

        # return ch to the pool
        with patch("pyon.net.messaging.log"):
            self._node.on_channel_request_close(ch)

        # expect to have bidir pool of two, pool map of 1
        self.assertEquals(len(self._node._bidir_pool), 2)
        self.assertEquals(len(self._node._pool_map), 1)

        # ch2 still active so it should be in the pool map
        self.assertIn(sentinel.chid2, self._node._pool_map)
Example #6
0
    def layer_vars(self, request, dummy_input_layer, DenseLayer):
        input_shape = dummy_input_layer.shape
        num_units = 5
        num_leading_axes = request.param
        W_shape = (np.prod(input_shape[num_leading_axes:]), num_units)
        b_shape = (num_units,)

        W = Mock()
        b = Mock()
        nonlinearity = Mock()
        W.return_value = np.arange(np.prod(W_shape)).reshape(W_shape)
        b.return_value = np.arange(np.prod(b_shape)).reshape(b_shape) * 3
        layer = DenseLayer(
            dummy_input_layer,
            num_units=num_units,
            num_leading_axes=num_leading_axes,
            W=W,
            b=b,
            nonlinearity=nonlinearity,
        )

        return {
            "input_shape": input_shape,
            "num_units": num_units,
            "num_leading_axes": num_leading_axes,
            "W_shape": W_shape,
            "b_shape": b_shape,
            "W": W,
            "b": b,
            "nonlinearity": nonlinearity,
            "layer": layer,
        }
Example #7
0
    def test_channel_pool_release_reacquire(self, bcbmock):
        ncm = Mock()
        ncm.return_value = Mock(spec=BidirClientChannel)
        ncm.return_value._queue_auto_delete = False
        ncm.return_value.get_channel_id.return_value = sentinel.chid

        with patch("pyon.net.messaging.NodeB._new_channel", ncm):
            ch = self._node.channel(BidirClientChannel)

        # return value is not a mock factory - it returns the same mock instance as we declared above
        # so redeclare it so they get unique chids
        ncm.return_value = Mock(spec=BidirClientChannel)
        ncm.return_value._queue_auto_delete = False
        ncm.return_value.get_channel_id.return_value = sentinel.chid2
        with patch("pyon.net.messaging.NodeB._new_channel", ncm):
            ch2 = self._node.channel(BidirClientChannel)

        self.assertEquals(ch.get_channel_id(), sentinel.chid)
        self.assertEquals(ch2.get_channel_id(), sentinel.chid2)

        # return ch to the pool
        with patch("pyon.net.messaging.log"):
            self._node.on_channel_request_close(ch)

        # reacquire ch
        call_count = ncm.call_count
        with patch("pyon.net.messaging.NodeB._new_channel", ncm):
            ch3 = self._node.channel(BidirClientChannel)
            # no new calls to the create method have been made
            self.assertEquals(ncm.call_count, call_count)

        # we got the first mocked channel back
        self.assertEquals(ch3.get_channel_id(), sentinel.chid)
Example #8
0
def test_get_all_without_clauses(get_query_clauses):
    """
    Test :py:meth:`~.BaseRallyModel.get_all` with no clauses passed in.

    Test that:
        * ``get_all`` does not call ``get_query_clauses``
        * Calls ``get_all_results_for_query`` with a blank query.
        * returns the set of objects as returned by
          ``convert_from_query_result``
    """
    DummyClass = get_inherited_class_object()

    mock_get_all_results_for_query = Mock()
    mock_get_all_results_for_query.return_value = "mock_results"
    mock_convert_from_query_result = Mock()
    mock_convert_from_query_result.return_value = "mock_conversion"
    DummyClass.get_all_results_for_query = mock_get_all_results_for_query
    DummyClass.convert_from_query_result = mock_convert_from_query_result

    response = DummyClass.get_all()

    assert_false(get_query_clauses.called)
    assert_equal(mock_get_all_results_for_query.call_args[0][0], "")
    assert_equal(mock_convert_from_query_result.call_args[0][0], "mock_results")
    assert_equal(response, "mock_conversion")
Example #9
0
def test_get_all_with_clauses(get_query_clauses):
    """
    Test :py:meth:`~.BaseRallyModel.get_all` with clauses passed in.

    Test that:
        * ``get_all`` calls ``get_query_clauses``
        * Uses the result to call ``get_all_results_for_query``
        * returns the set of objects as returned by
          ``convert_from_query_result``
    """
    DummyClass = get_inherited_class_object()

    get_query_clauses.return_value = "mock_query"

    mock_get_all_results_for_query = Mock()
    mock_get_all_results_for_query.return_value = "mock_results"
    mock_convert_from_query_result = Mock()
    mock_convert_from_query_result.return_value = "mock_conversion"
    DummyClass.get_all_results_for_query = mock_get_all_results_for_query
    DummyClass.convert_from_query_result = mock_convert_from_query_result

    response = DummyClass.get_all("clauses")

    assert_equal(get_query_clauses.call_args[0][0], "clauses")
    assert_equal(mock_get_all_results_for_query.call_args[0][0], "mock_query")
    assert_equal(mock_convert_from_query_result.call_args[0][0], "mock_results")
    assert_equal(response, "mock_conversion")
    def test_rmtree_success(self):
        dir1_list = ["dir2", "file"]
        empty_list = []
        mock_listdir = Mock()
        mock_listdir.side_effect = [dir1_list, empty_list]

        mock_isdir = Mock()
        mock_isdir.side_effect = [True, False]

        mock_unlink = Mock()
        mock_unlink.return_value = 0

        mock_rmdir = Mock()
        mock_rmdir.return_value = 0

        mock_islink = Mock()
        mock_islink.return_value = False

        with nested(
            patch("gluster.gfapi.Volume.listdir", mock_listdir),
            patch("gluster.gfapi.Volume.isdir", mock_isdir),
            patch("gluster.gfapi.Volume.islink", mock_islink),
            patch("gluster.gfapi.Volume.unlink", mock_unlink),
            patch("gluster.gfapi.Volume.rmdir", mock_rmdir),
        ):
            self.vol.rmtree("dir1")
            mock_rmdir.assert_any_call("dir1/dir2")
            mock_unlink.assert_called_once_with("dir1/file")
            mock_rmdir.assert_called_with("dir1")
Example #11
0
    def layer_vars(self, NINLayer_c01b, dummy_input_layer):
        W = Mock()
        b = Mock()
        nonlinearity = Mock()

        W.return_value = np.ones((5, 3))
        b.return_value = np.ones((5,))
        layer = NINLayer_c01b(dummy_input_layer, num_units=5, W=W, b=b, nonlinearity=nonlinearity)

        return {"W": W, "b": b, "nonlinearity": nonlinearity, "layer": layer}
    def test_makedirs_fail_exception(self):
        mock_glfs_mkdir = Mock()
        mock_glfs_mkdir.return_value = -1

        mock_exists = Mock()
        mock_exists.return_value = False

        with nested(
            patch("gluster.gfapi.api.glfs_mkdir", mock_glfs_mkdir), patch("gluster.gfapi.Volume.exists", mock_exists)
        ):
            self.assertRaises(OSError, self.vol.makedirs, "dir1/dir2", 0775)
def mock_urlopen(retval, exception=None, bad_response=False):
    urlopen = Mock()
    if bad_response:
        urlopen.return_value = StringIO(unicode([1, 2, "hello"]))
    elif exception:
        urlopen.side_effect = exception
    elif retval is None:
        urlopen.return_value = StringIO(unicode([]))
    else:
        urlopen.return_value = StringIO(unicode([retval]))
    return urlopen
Example #14
0
def test_sudo_support():
    fn = Mock(return_value=True, __name__="")
    assert sudo_support(fn)(Command("sudo ls"), None)
    fn.assert_called_once_with(Command("ls"), None)

    fn.return_value = False
    assert not sudo_support(fn)(Command("sudo ls"), None)

    fn.return_value = "pwd"
    assert sudo_support(fn)(Command("sudo ls"), None) == "sudo pwd"

    assert sudo_support(fn)(Command("ls"), None) == "pwd"
Example #15
0
 def test_find_with_postcode_errors(self):
     """ Tests boris.BikeChecker.find_with_postcode exceptions """
     get_mock = Mock(return_value=None)
     patcher = patch.object(self.bc, "pc", new=Mock(get=get_mock))
     patcher.start()
     f = self.bc.find_with_postcode
     self.assertRaises(InvalidPostcodeException, f, None)
     get_mock.return_value = {"foo": "bar"}
     self.assertRaises(InvalidDataException, f, None)
     get_mock.return_value = {"geo": {"lat": 0}}
     self.assertRaises(InvalidDataException, f, None)
     patcher.stop()
Example #16
0
    def layer_vars(self, dummy_input_layer):
        from lasagne.layers.dense import DenseLayer

        W = Mock()
        b = Mock()
        nonlinearity = Mock()

        W.return_value = np.ones((12, 3))
        b.return_value = np.ones((3,)) * 3
        layer = DenseLayer(dummy_input_layer, num_units=3, W=W, b=b, nonlinearity=nonlinearity)

        return {"W": W, "b": b, "nonlinearity": nonlinearity, "layer": layer}
    def test_cloud_service(self):
        mock = Mock()
        self.service.service.get_hosted_service_properties = mock

        mock.return_value = True
        self.assertTrue(self.service.cloud_service_exists(test_conf.meanless_name))

        mock.return_value = None
        self.assertFalse(self.service.cloud_service_exists(test_conf.meanless_name))

        mock.side_effect = AzureMissingResourceHttpError(233, 233)
        self.assertFalse(self.service.cloud_service_exists(test_conf.meanless_name))
    def test_buildslave_shutdown(self):
        """Test watching an existing shutdown_file results in gracefulShutdown
        being called."""

        buildslave = bot.BuildSlave(
            "127.0.0.1",
            1234,
            "testy",
            "westy",
            self.basedir,
            keepalive=0,
            usePTY=False,
            umask=0o22,
            allow_shutdown="file",
        )

        # Mock out gracefulShutdown
        buildslave.gracefulShutdown = Mock()

        # Mock out os.path methods
        exists = Mock()
        mtime = Mock()

        self.patch(os.path, "exists", exists)
        self.patch(os.path, "getmtime", mtime)

        # Pretend that the shutdown file doesn't exist
        mtime.return_value = 0
        exists.return_value = False

        buildslave._checkShutdownFile()

        # We shouldn't have called gracefulShutdown
        self.assertEquals(buildslave.gracefulShutdown.call_count, 0)

        # Pretend that the file exists now, with an mtime of 2
        exists.return_value = True
        mtime.return_value = 2
        buildslave._checkShutdownFile()

        # Now we should have changed gracefulShutdown
        self.assertEquals(buildslave.gracefulShutdown.call_count, 1)

        # Bump the mtime again, and make sure we call shutdown again
        mtime.return_value = 3
        buildslave._checkShutdownFile()
        self.assertEquals(buildslave.gracefulShutdown.call_count, 2)

        # Try again, we shouldn't call shutdown another time
        buildslave._checkShutdownFile()
        self.assertEquals(buildslave.gracefulShutdown.call_count, 2)
Example #19
0
    def layer_vars(self):
        from lasagne.layers.dense import DenseLayer

        input_layer = Mock()
        W = Mock()
        b = Mock()
        nonlinearity = Mock()

        input_layer.get_output_shape.return_value = (2, 3, 4)
        W.return_value = numpy.ones((12, 3))
        b.return_value = numpy.ones((3,)) * 3
        layer = DenseLayer(input_layer=input_layer, num_units=3, W=W, b=b, nonlinearity=nonlinearity)

        return {"W": W, "b": b, "nonlinearity": nonlinearity, "layer": layer}
Example #20
0
    def test_VerifyPath(self):
        entry = lxml.etree.Element("Path", name="test", type="file")
        modlist = []

        mock_verify = Mock()
        mock_verify.return_value = True
        self.posix._handlers[entry.get("type")].verify = mock_verify
        self.assertTrue(self.posix.VerifyPath(entry, modlist))
        mock_verify.assert_called_with(entry, modlist)

        mock_verify.reset_mock()
        mock_verify.return_value = False
        self.posix.setup.__getitem__.return_value = True
        self.assertFalse(self.posix.VerifyPath(entry, modlist))
        self.assertIsNotNone(entry.get("qtext"))
Example #21
0
    def test_use_GET_in(self):
        fn, request = Mock(), Mock()
        request.GET.lists.return_value = [("param1", [0]), ("param2", [-1])]

        # Dictionaries become JSON
        fn.return_value = {"a": 1, "b": 2}
        response = use_GET_in(fn, request)
        self.assertEqual(json.loads(response.content), {"a": 1, "b": 2})
        self.assertEqual(fn.call_args[0][0], {"param1": [0], "param2": [-1]})

        # Everything else is unaltered
        fn.return_value = HttpResponseNotFound("Oh noes")
        response = use_GET_in(fn, request)
        self.assertEqual(response.status_code, 404)
        self.assertEqual(response.content, "Oh noes")
    def testAlwaysRunStepStopBuild(self):
        """Test that steps marked with alwaysRun=True still get run even if
        the build is stopped."""

        # Create a build with 2 steps, the first one will get interrupted, and
        # the second one is marked with alwaysRun=True
        r = FakeRequest()

        b = Build([r])
        b.setBuilder(Mock())

        step1 = Mock()
        step1.return_value = step1
        step1.alwaysRun = False
        step2 = Mock()
        step2.return_value = step2
        step2.alwaysRun = True
        b.setStepFactories([(step1, {}), (step2, {})])

        slavebuilder = Mock()
        status = Mock()

        def startStep1(*args, **kw):
            # Now interrupt the build
            b.stopBuild("stop it")
            return defer.succeed(SUCCESS)

        step1.startStep = startStep1
        step1.stepDone.return_value = False

        step2Started = [False]

        def startStep2(*args, **kw):
            step2Started[0] = True
            return defer.succeed(SUCCESS)

        step2.startStep = startStep2
        step1.stepDone.return_value = False

        d = b.startBuild(status, None, slavebuilder)

        def check(ign):
            self.assertEqual(b.result, EXCEPTION)
            self.assert_(("interrupt", ("stop it",), {}) in step1.method_calls)
            self.assert_(step2Started[0])

        d.addCallback(check)
        return d
    def test_call(self):
        mock = Mock()
        self.assertTrue(is_instance(mock.return_value, Mock), "Default return_value should be a Mock")

        result = mock()
        self.assertEqual(mock(), result, "different result from consecutive calls")
        mock.reset_mock()

        ret_val = mock(sentinel.Arg)
        self.assertTrue(mock.called, "called not set")
        self.assertEqual(mock.call_count, 1, "call_count incoreect")
        self.assertEqual(mock.call_args, ((sentinel.Arg,), {}), "call_args not set")
        self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})], "call_args_list not initialised correctly")

        mock.return_value = sentinel.ReturnValue
        ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
        self.assertEqual(ret_val, sentinel.ReturnValue, "incorrect return value")

        self.assertEqual(mock.call_count, 2, "call_count incorrect")
        self.assertEqual(mock.call_args, ((sentinel.Arg,), {"key": sentinel.KeyArg}), "call_args not set")
        self.assertEqual(
            mock.call_args_list,
            [((sentinel.Arg,), {}), ((sentinel.Arg,), {"key": sentinel.KeyArg})],
            "call_args_list not set",
        )
Example #24
0
    def test_recv_edu(self):
        recv_observer = Mock()
        recv_observer.return_value = defer.succeed(())

        self.federation.register_edu_handler("m.test", recv_observer)

        yield self.mock_resource.trigger(
            "PUT",
            "/_matrix/federation/v1/send/1001000/",
            """{
                "origin": "remote",
                "origin_server_ts": 1001000,
                "pdus": [],
                "edus": [
                    {
                        "origin": "remote",
                        "destination": "test",
                        "edu_type": "m.test",
                        "content": {"testing": "reply here"}
                    }
                ]
            }""",
        )

        recv_observer.assert_called_with("remote", {"testing": "reply here"})
Example #25
0
 def create_mock_api_factory(cls):
     """Create a collection of mocks for a test that wants to mock out the client API
 by patching the api factory."""
     mock_api, mock_scheduler_proxy = cls.create_mock_api()
     mock_api_factory = Mock()
     mock_api_factory.return_value = mock_api
     return mock_api_factory, mock_scheduler_proxy
Example #26
0
 def test_with_defaults(self, objective, get_output):
     loss_function, target = Mock(), Mock()
     loss_function.return_value = np.array([1, 2, 3])
     result = objective([1, 2, 3], loss_function=loss_function, target=target)
     assert result == 2.0
     get_output.assert_called_with(3, deterministic=False)
     loss_function.assert_called_with(get_output.return_value, target)
Example #27
0
    def get_csrf_request(self, post=None):
        csrf = "abc"

        if not u"_csrf" in post.keys():
            post.update({"_csrf": csrf})

        # We can't use dummyrequest cause the simpleform
        # needs MultiDict and NestedMultiDict from WebOb request
        # This is the 'real' request.
        from webob.multidict import MultiDict, NestedMultiDict

        multidict = MultiDict()
        # This is my own invention. Use with caution :)
        # request = Request.blank('/', method="POST", registry=registry)

        for key in post.keys():
            multidict[key] = post[key]

        request = testing.DummyRequest(post=multidict, params=NestedMultiDict(multidict))
        request.session = Mock()
        csrf_token = Mock()
        csrf_token.return_value = csrf

        request.session.get_csrf_token = csrf_token
        request.root = self.zodb
        return request
Example #28
0
    def testStopBuildWaitingForLocks_lostRemote(self):
        b = self.build

        slavebuilder = Mock()

        l = SlaveLock("lock")
        lock_access = l.access("counting")
        l.access = lambda mode: lock_access
        real_lock = b.builder.botmaster.getLockByID(l).getLock(slavebuilder)
        b.setLocks([lock_access])

        step = Mock()
        step.return_value = step
        step.startStep.return_value = SUCCESS
        step.alwaysRun = False
        b.setStepFactories([FakeStepFactory(step)])

        real_lock.claim(Mock(), l.access("counting"))

        def acquireLocks(res=None):
            retval = Build.acquireLocks(b, res)
            b.lostRemote()
            return retval

        b.acquireLocks = acquireLocks

        b.startBuild(FakeBuildStatus(), None, slavebuilder)

        self.assert_(("startStep", (slavebuilder.remote,), {}) not in step.method_calls)
        self.assert_(b.currentStep is None)
        self.assertEqual(b.result, RETRY)
        self.assert_(("interrupt", ("stop it",), {}) not in step.method_calls)
        self.build.build_status.setText.assert_called_with(["retry", "lost", "remote"])
        self.build.build_status.setResults.assert_called_with(RETRY)
Example #29
0
    def testBuildWaitingForLocks(self):
        b = self.build

        slavebuilder = Mock()

        l = SlaveLock("lock")
        claimCount = [0]
        lock_access = l.access("counting")
        l.access = lambda mode: lock_access
        real_lock = b.builder.botmaster.getLockByID(l).getLock(slavebuilder.slave)

        def claim(owner, access):
            claimCount[0] += 1
            return real_lock.old_claim(owner, access)

        real_lock.old_claim = real_lock.claim
        real_lock.claim = claim
        b.setLocks([lock_access])

        step = Mock()
        step.return_value = step
        step.startStep.return_value = SUCCESS
        b.setStepFactories([FakeStepFactory(step)])

        real_lock.claim(Mock(), l.access("counting"))

        b.startBuild(FakeBuildStatus(), None, slavebuilder)

        self.assert_(("startStep", (slavebuilder.remote,), {}) not in step.method_calls)
        self.assertEquals(claimCount[0], 1)
        self.assert_(b.currentStep is None)
        self.assert_(b._acquiringLock is not None)
Example #30
0
    def testStopBuildWaitingForLocks(self):
        b = self.build

        l = SlaveLock("lock")
        lock_access = l.access("counting")
        l.access = lambda mode: lock_access
        real_lock = b.builder.botmaster.getLockByID(l).getLock(self.slavebuilder.slave)
        b.setLocks([lock_access])

        step = Mock()
        step.return_value = step
        step.startStep.return_value = SUCCESS
        step.alwaysRun = False
        b.setStepFactories([FakeStepFactory(step)])

        real_lock.claim(Mock(), l.access("counting"))

        def acquireLocks(res=None):
            retval = Build.acquireLocks(b, res)
            b.stopBuild("stop it")
            return retval

        b.acquireLocks = acquireLocks

        b.startBuild(FakeBuildStatus(), None, self.slavebuilder)

        self.assert_(("startStep", (self.slavebuilder.slave.conn,), {}) not in step.method_calls)
        self.assert_(b.currentStep is None)
        self.assertEqual(b.result, CANCELLED)
        self.assert_(("interrupt", ("stop it",), {}) not in step.method_calls)