Example #1
0
    def test_step_status_is_collected_and_reported(self, format_summary, stdout):
        feature = Mock()
        scenario = Mock()
        steps = [Mock(), Mock(), Mock(), Mock(), Mock()]
        steps[0].status = Status.failed
        steps[0].__iter__ = Mock(return_value=iter([]))
        steps[1].status = Status.passed
        steps[1].__iter__ = Mock(return_value=iter([]))
        steps[2].status = Status.passed
        steps[2].__iter__ = Mock(return_value=iter([]))
        steps[3].status = Status.skipped
        steps[4].__iter__ = Mock(return_value=iter([]))
        steps[4].status = Status.undefined
        steps[4].__iter__ = Mock(return_value=iter([]))
        feature.status = Status.failed
        feature.duration = 12.3
        feature.__iter__ = Mock(return_value=iter([scenario]))
        scenario.status = Status.failed
        scenario.__iter__ = Mock(return_value=iter(steps))

        config = Mock()
        reporter = SummaryReporter(config)

        reporter.feature(feature)
        reporter.end()

        expected = {
            Status.passed.name: 2,
            Status.failed.name: 1,
            Status.skipped.name: 1,
            Status.untested.name: 0,
            Status.undefined.name: 1,
        }

        eq_(format_summary.call_args_list[2][0], ("step", expected))
Example #2
0
    def test_step_status_is_collected_and_reported(self, format_summary, stderr):
        # pylint: disable=W0621
        #   W0621   Redefining name ... from outer scope (format_summary)
        feature = Mock()
        scenario = Mock()
        steps = [Mock(), Mock(), Mock(), Mock(), Mock()]
        steps[0].status = "failed"
        steps[0].__iter__ = Mock(return_value=iter([]))
        steps[1].status = "undefined"
        steps[1].__iter__ = Mock(return_value=iter([]))
        steps[2].status = "passed"
        steps[2].__iter__ = Mock(return_value=iter([]))
        steps[3].status = "passed"
        steps[3].__iter__ = Mock(return_value=iter([]))
        steps[4].status = None
        steps[4].__iter__ = Mock(return_value=iter([]))
        feature.status = "failed"
        feature.duration = 12.3
        feature.__iter__ = Mock(return_value=iter([scenario]))
        scenario.status = "failed"
        scenario.__iter__ = Mock(return_value=iter(steps))

        config = Mock()
        reporter = SummaryReporter(config)

        reporter.feature(feature)
        reporter.end()

        expected = {"passed": 2, "failed": 1, "skipped": 1, "untested": 0, "undefined": 1}

        eq_(format_summary.call_args_list[2][0], ("step", expected))
    def testGetSuggestedInstancesTwoDifferentSize(self, getRDSInstancesMock):
        region = "us-west-2"
        # Instance 1
        instanceMock1 = Mock(spec="boto.rds.dbinstance.DBInstance")
        instanceMock1.status = "available"
        instanceMock1.allocated_storage = 64.0
        instanceMock1.id = "testId1"
        # Instance 2
        instanceMock2 = Mock(spec="boto.rds.dbinstance.DBInstance")
        instanceMock2.status = "available"
        instanceMock2.allocated_storage = 65.0
        instanceMock2.id = "testId2"

        getRDSInstancesMock.return_value = [instanceMock1, instanceMock2]

        suggestions = rds_utils.getSuggestedInstances(region)
        self.assertIsInstance(suggestions, types.GeneratorType)
        suggestions = list(suggestions)

        self.assertSequenceEqual(
            suggestions,
            [
                {"id": "testId2", "name": "testId2", "namespace": "AWS/RDS", "region": region},
                {"id": "testId1", "name": "testId1", "namespace": "AWS/RDS", "region": region},
            ],
        )
        getRDSInstancesMock.assert_call_once_with(region)
Example #4
0
def test_catter():
    fs = Filesystem(DB(":memory:"))
    fs.root().add_file("zeroes", [test_asset_ids])

    asset = Mock()
    asset.__enter__ = Mock(return_value=asset)
    asset.__exit__ = Mock(return_value=False)
    asset.status = Mock(return_value=proto.AssetStatus(size=1024 * 1024, status=proto.SUCCESS))
    asset.__iter__ = Mock(return_value=("\x00" * (128 * 1024) for _ in range(8)))

    bithorde = Mock()
    bithorde.open = Mock(return_value=asset)
    cat = Cat(fs, bithorde)

    sha = sha1()
    for chunk in cat(P("zeroes")):
        sha.update(chunk)
    assert_equals(sha.hexdigest(), "3b71f43ff30f4b15b5cd85dd9e95ebc7e84eb5a3")

    with assert_raises(FNotFound):
        for chunk in cat(P("NON-EXISTING")):
            pass

    asset.status = Mock(return_value=proto.AssetStatus(status=proto.NOTFOUND))
    with assert_raises(NotFoundError):
        for chunk in cat(P("zeroes")):
            pass
    def test_request(self):
        self.hc.USER_AGENT = "user-agent"
        resp = Mock()
        body = Mock()
        resp.status = 200
        httplib2.Http.request = Mock(return_value=(resp, body))
        self.hc.morph_response_body = Mock(return_value=body)
        r, b = self.hc.request()
        self.assertEqual(resp, r)
        self.assertEqual(body, b)
        self.assertEqual((resp, body), self.hc.last_response)

        httplib2.Http.request = Mock(return_value=(resp, None))
        r, b = self.hc.request()
        self.assertEqual(resp, r)
        self.assertEqual(None, b)

        status_list = [400, 401, 403, 404, 408, 409, 413, 500, 501]
        for status in status_list:
            resp.status = status
            self.assertRaises(Exception, self.hc.request)

        exception = exceptions.ResponseFormatError
        self.hc.morph_response_body = Mock(side_effect=exception)
        self.assertRaises(Exception, self.hc.request)
Example #6
0
    def test_retry_successfull(self, mock_get_connection):
        # this tests the read function when first HTTP request returns a 503 but the second one
        # is successfull and returns a 200

        # mock the 503 response
        mockHttpResponse503 = Mock(name="HttpResponse503")
        mockHttpResponse503.getheader.return_value = 1
        mockHttpResponse503.status = 503
        mockHttpResponse503.read.return_value = "Fail"
        mockHttpResponse503.len.return_value = 10

        # mock the 200 response
        mockHttpResponse200 = Mock(name="HttpResponse200")
        mockHttpResponse200.getheader.return_value = 1
        mockHttpResponse200.status = 200
        mockHttpResponse200.read.return_value = "Testing"
        mockHttpResponse200.len.return_value = 10
        conn = Connection()
        mockHttpRequest = Mock(name="HttpRequest")

        # set a 503 response first followed by a 200 response
        mockHttpRequest.getresponse = MagicMock(name="getresponse mock")
        generator = mockHttpRequest.getresponse.iter.return_value
        iterator = iter([mockHttpResponse503, mockHttpResponse200])
        generator.__iter__.return_value = iterator
        conn.get_connection.return_value = mockHttpRequest
        # vofile = vos.VOFile(["Some URL"], mockConn, "GET")
        vofile = vos.VOFile(["Some URL"], conn, "GET")
Example #7
0
 def create_mock_scheduled_tasks(cls):
     jobs = []
     for name in ["foo", "bar", "baz"]:
         job = Mock()
         job.key = JobKey(role=cls.TEST_ROLE, environment=cls.TEST_ENV, name=name)
         job.failure_count = 0
         job.assignedTask = Mock(spec=AssignedTask)
         job.assignedTask.slaveHost = "slavehost"
         job.assignedTask.task = Mock(spec=TaskConfig)
         job.assignedTask.task.maxTaskFailures = 1
         job.assignedTask.task.executorConfig = Mock(spec=ExecutorConfig)
         job.assignedTask.task.executorConfig.data = Mock()
         job.assignedTask.task.packages = []
         job.assignedTask.task.owner = Identity(role="mchucarroll")
         job.assignedTask.task.environment = "test"
         job.assignedTask.task.jobName = "woops"
         job.assignedTask.task.numCpus = 2
         job.assignedTask.task.ramMb = 2
         job.assignedTask.task.diskMb = 2
         job.assignedTask.instanceId = 4237894
         job.assignedTask.assignedPorts = None
         job.status = ScheduleStatus.RUNNING
         mockEvent = Mock(spec=TaskEvent)
         mockEvent.timestamp = 28234726395
         mockEvent.status = ScheduleStatus.RUNNING
         mockEvent.message = "Hi there"
         job.taskEvents = [mockEvent]
         jobs.append(job)
     return jobs
Example #8
0
 def test_delete(self):
     resp = Mock()
     resp.status = 200
     body = None
     self.instances.api.client.delete = Mock(return_value=(resp, body))
     self.instances.delete("instance1")
     resp.status = 500
     self.assertRaises(Exception, self.instances.delete, "instance1")
 def test__action(self):
     resp = Mock()
     self.management.api.client.post = Mock(return_value=(resp, "body"))
     resp.status = 200
     self.management._action(1, "body")
     self.assertEqual(1, self.management.api.client.post.call_count)
     resp.status = 400
     self.assertRaises(ValueError, self.management._action, 1, "body")
     self.assertEqual(2, self.management.api.client.post.call_count)
    def test_raise_error_from_status(self):
        resp = Mock()
        resp.status = 200
        self.hc.raise_error_from_status(resp, Mock())

        status_list = [400, 401, 403, 404, 408, 409, 413, 500, 501]
        for status in status_list:
            resp.status = status
            self.assertRaises(Exception, self.hc.raise_error_from_status, resp, Mock())
 def test_delete(self):
     resp = Mock()
     resp.status = 200
     body = None
     self.security_group_rules.api = Mock()
     self.security_group_rules.api.client = Mock()
     self.security_group_rules.api.client.delete = Mock(return_value=(resp, body))
     self.security_group_rules.delete(self.id)
     resp.status = 500
     self.assertRaises(Exception, self.security_group_rules.delete, self.id)
 def test_index(self):
     resp = Mock()
     resp.status = 400
     body = {"Accounts": {}}
     self.accounts.api.client.get = Mock(return_value=(resp, body))
     self.assertRaises(Exception, self.accounts.index)
     resp.status = 200
     self.assertTrue(isinstance(self.accounts.index(), base.Resource))
     self.accounts.api.client.get = Mock(return_value=(resp, None))
     self.assertRaises(Exception, self.accounts.index)
    def test_check_for_exceptions(self):
        status = [400, 422, 500]
        for s in status:
            resp = Mock()
            resp.status = s
            self.assertRaises(ValueError, common.check_for_exceptions, resp, "body")

        # a no-exception case
        resp = Mock()
        resp.status = 200
        common.check_for_exceptions(resp, "body")
Example #14
0
    def test_edit_save_errors(self):
        self.client.post(settings.LOGIN_URL, ADMIN_CREDENTIALS)
        data = self.edit_mgmt_data.copy()
        data.update({"title": "foo", "description": "bar", "creator": "baz", "file_name": "foo.txt"})
        # simulate fedora errors with mock objects
        testobj = Mock(spec=FileObject, name="MockDigitalObject")
        # django templates recognize this as a callable; set to return itself when called
        testobj.return_value = testobj
        # create a Mock object, but use a DublinCore instance for xmlobjectform to inspect
        testobj.dc.content = DublinCore()
        testobj.pid = "pid:1"  # required for url generation
        # Create a RequestFailed exception to simulate Fedora error
        # - eulcore.fedora wrap around an httplib response
        err_resp = Mock()
        err_resp.status = 500
        err_resp.read.return_value = "error message"
        # generate Fedora error on object save
        testobj.save.side_effect = RequestFailed(err_resp)

        # 500 error / request failed
        # patch the repository class to return the mock object instead of a real one
        # with patch.object(Repository, 'get_object', new=Mock(return_value=testobj)):
        with patch("genrepo.file.views.init_by_cmodel", new=Mock(return_value=testobj)):
            response = self.client.post(self.edit_url, data, follow=True)
            expected, code = 500, response.status_code
            self.assertEqual(
                code,
                expected,
                "Expected %s but returned %s for %s (Fedora 500 error)" % (expected, code, self.edit_url),
            )
            messages = [str(msg) for msg in response.context["messages"]]
            self.assert_("error communicating with the repository" in messages[0])

        # update the mock object to generate a permission denied error
        err_resp.status = 401
        err_resp.read.return_value = "denied"
        # generate Fedora error on object save
        testobj.save.side_effect = PermissionDenied(err_resp)

        # 401 error -  permission denied
        # with patch.object(Repository, 'get_object', new=Mock(return_value=testobj)):
        with patch("genrepo.file.views.init_by_cmodel", new=Mock(return_value=testobj)):
            response = self.client.post(self.edit_url, data, follow=True)
            expected, code = 401, response.status_code
            self.assertEqual(
                code,
                expected,
                "Expected %s but returned %s for %s (Fedora 401 error)" % (expected, code, self.edit_url),
            )
            messages = [str(msg) for msg in response.context["messages"]]
            self.assert_("You don't have permission to modify this object" in messages[0])
Example #15
0
    def test_create_save_errors(self):
        "Test fedora error handling when saving a collection object"
        # simulate fedora errors with mock objects

        # log in as repository editor
        self.client.post(settings.LOGIN_URL, ADMIN_CREDENTIALS)

        testobj = Mock(name="MockDigitalObject")
        testobj.dc.content = DublinCore()
        # Create a RequestFailed exception to simulate Fedora error
        # - eulcore.fedora wrap around an httplib response
        err_resp = Mock()
        err_resp.status = 500
        err_resp.read.return_value = "error message"
        # generate Fedora error on object save
        testobj.save.side_effect = RequestFailed(err_resp)

        # valid form data to post
        test_data = {"title": "foo", "description": "bar"}

        # 500 error / request failed
        # patch the repository class to return the mock object instead of a real one
        with patch.object(Repository, "get_object", new=Mock(return_value=testobj)):
            response = self.client.post(self.new_coll_url, test_data, follow=True)
            expected, code = 500, response.status_code
            self.assertEqual(
                code,
                expected,
                "Expected %s but returned %s for %s (Fedora 500 error)" % (expected, code, self.new_coll_url),
            )
            messages = [str(msg) for msg in response.context["messages"]]
            self.assert_("error communicating with the repository" in messages[0])

        # update the mock error to generate a permission denied error
        err_resp.status = 401
        err_resp.read.return_value = "denied"
        # generate Fedora error on object save
        testobj.save.side_effect = PermissionDenied(err_resp)

        # 401 error -  permission denied
        with patch.object(Repository, "get_object", new=Mock(return_value=testobj)):
            response = self.client.post(self.new_coll_url, test_data, follow=True)
            expected, code = 401, response.status_code
            self.assertEqual(
                code,
                expected,
                "Expected %s but returned %s for %s (Fedora 401 error)" % (expected, code, self.new_coll_url),
            )
            messages = [str(msg) for msg in response.context["messages"]]
            self.assert_("You don't have permission to create a collection" in messages[0])
Example #16
0
    def test_version(self):
        from pgxnclient import Spec
        from pgxnclient.commands.install import Download
        from pgxnclient.errors import ResourceNotFound

        opt = Mock()
        opt.status = Spec.STABLE
        cmd = Download(opt)

        for spec, res, data in [
            ("foo", "1.2.0", {"stable": ["1.2.0"]}),
            ("foo", "1.2.0", {"stable": ["1.2.0", "1.2.0b"]}),
            ("foo=1.2", "1.2.0", {"stable": ["1.2.0"]}),
            ("foo>=1.1", "1.2.0", {"stable": ["1.1.0", "1.2.0"]}),
            ("foo>=1.1", "1.2.0", {"stable": ["1.1.0", "1.2.0"], "testing": ["1.3.0"], "unstable": ["1.4.0"]}),
        ]:
            spec = Spec.parse(spec)
            data = {"releases": dict([(k, [{"version": v} for v in vs]) for k, vs in data.items()])}

            self.assertEqual(res, cmd.get_best_version(data, spec))

        for spec, res, data in [
            ("foo>=1.3", "1.2.0", {"stable": ["1.2.0"]}),
            ("foo>=1.3", "1.2.0", {"stable": ["1.2.0"], "testing": ["1.3.0"]}),
        ]:
            spec = Spec.parse(spec)
            data = {"releases": dict([(k, [{"version": v} for v in vs]) for k, vs in data.items()])}

            self.assertRaises(ResourceNotFound, cmd.get_best_version, data, spec)

        opt.status = Spec.TESTING

        for spec, res, data in [
            ("foo>=1.1", "1.3.0", {"stable": ["1.1.0", "1.2.0"], "testing": ["1.3.0"], "unstable": ["1.4.0"]})
        ]:
            spec = Spec.parse(spec)
            data = {"releases": dict([(k, [{"version": v} for v in vs]) for k, vs in data.items()])}

            self.assertEqual(res, cmd.get_best_version(data, spec))

        opt.status = Spec.UNSTABLE

        for spec, res, data in [
            ("foo>=1.1", "1.4.0", {"stable": ["1.1.0", "1.2.0"], "testing": ["1.3.0"], "unstable": ["1.4.0"]})
        ]:
            spec = Spec.parse(spec)
            data = {"releases": dict([(k, [{"version": v} for v in vs]) for k, vs in data.items()])}

            self.assertEqual(res, cmd.get_best_version(data, spec))
Example #17
0
    def test_scenario_outline_status_is_collected_and_reported(self, stdout, format_summary):
        feature = Mock()
        scenarios = [ScenarioOutline(u"<string>", 0, u"scenario_outline", u"name"), Mock(), Mock(), Mock()]
        subscenarios = [Mock(), Mock(), Mock(), Mock()]
        subscenarios[0].status = Status.passed
        subscenarios[0].__iter__ = Mock(return_value=iter([]))
        subscenarios[1].status = Status.failed
        subscenarios[1].__iter__ = Mock(return_value=iter([]))
        subscenarios[2].status = Status.failed
        subscenarios[2].__iter__ = Mock(return_value=iter([]))
        subscenarios[3].status = Status.skipped
        subscenarios[3].__iter__ = Mock(return_value=iter([]))
        scenarios[0]._scenarios = subscenarios
        scenarios[1].status = Status.failed
        scenarios[1].__iter__ = Mock(return_value=iter([]))
        scenarios[2].status = Status.skipped
        scenarios[2].__iter__ = Mock(return_value=iter([]))
        scenarios[3].status = Status.passed
        scenarios[3].__iter__ = Mock(return_value=iter([]))
        feature.status = Status.failed
        feature.duration = 12.4
        feature.__iter__ = Mock(return_value=iter(scenarios))

        config = Mock()
        reporter = SummaryReporter(config)

        reporter.feature(feature)
        reporter.end()

        expected = {Status.passed.name: 2, Status.failed.name: 3, Status.skipped.name: 2, Status.untested.name: 0}

        eq_(format_summary.call_args_list[1][0], ("scenario", expected))
Example #18
0
def test_DBExporter():
    path = u"apa/movie"
    xt = u"tree:tiger:ASDASDSADASDASDSADASDASDSADASDASDSADASD"
    db = DB(":memory:")
    db.update(Object(u"dir:apa", {u"directory": ValueSet(u"dir:/apa")}))
    db.update(Object("some_file", {u"directory": ValueSet(u"dir:apa/movie"), u"xt": ValueSet(xt)}))

    asset = Mock()
    asset.__enter__ = Mock(return_value=asset)
    asset.__exit__ = Mock(return_value=False)
    asset.status = Mock(return_value=proto.AssetStatus(status=proto.SUCCESS))

    bithorde = Mock()
    bithorde.open = Mock(return_value=asset)
    bithorde.pool = Mock(return_value=itertools)

    writer = Mock()

    magnet = u"magnet:?xt=urn:" + xt
    exp = links.DBExporter(db, bithorde, writer)
    exp.export(False)
    writer.assert_called_once_with(path, magnet)
    writer.reset_mock()

    exp.export(False)
    writer.assert_not_called()

    exp.export(True)
    writer.assert_called_once_with(path, magnet)
    def test_handle_wi(self):
        wid = Mock()
        wid.fields.project = "Test"
        wid.params.delete = False
        # Test: has attribute -> True
        # This means we don't need to schedule a nightly build
        self.participant.obs.projectAttributeExists.return_value = True
        self.participant.handle_wi(wid)
        self.assertFalse(wid.fields.needs_build)

        # Test: has attribute -> False
        # This means we schedule the nightly build
        self.participant.obs.projectAttributeExists.return_value = False
        self.participant.handle_wi(wid)
        self.assertTrue(wid.fields.needs_build)

        # Test: Project attribute deleted -> True
        # If so, return True
        wid.params.delete = True
        wid.status = False
        self.participant.obs.deleteProjectAttribute.return_value = True
        self.participant.handle_wi(wid)
        self.assertTrue(wid.status)

        # Test: Project attribute deleted -> False
        # If so, return False
        self.participant.obs.deleteProjectAttribute.return_value = False
        self.participant.handle_wi(wid)
        self.assertFalse(wid.status)
Example #20
0
 def get_backup_file(self):
     file = Mock()
     file.platform_id = amo.PLATFORM_ALL.id
     file.latest_xpi_url.return_value = "xpi.backup"
     file.get_url_path.return_value = "xpi.backup.url"
     file.status = amo.STATUS_PUBLIC
     return file
Example #21
0
    def test_should_maintain_count_of_tests_that_had_errors(self):
        suite = XunitSuite("errorsuite")
        test1 = Mock(XunitTest)
        test1.passed = False
        test1.status = "error"
        assert_that(suite.error_count, is_(0))

        suite.append(test1)
        assert_that(suite.error_count, is_(1))

        test2 = Mock(XunitTest)
        test2.passed = False
        test2.status = "failed"

        suite.append(test2)
        assert_that(suite.error_count, is_(1))
Example #22
0
    def test_scenario_outline_status_is_collected_and_reported(self, stderr, format_summary):
        # FIX: issue40
        # ENSURE: ScenarioOutline's scenarios are walked and collected.
        feature = Mock()
        scenarios = [ScenarioOutline(u"<string>", 0, u"scenario_outline", u"name"), Mock(), Mock(), Mock()]
        subscenarios = [Mock(), Mock(), Mock(), Mock()]
        subscenarios[0].status = "passed"
        subscenarios[0].__iter__ = Mock(return_value=iter([]))
        subscenarios[1].status = "failed"
        subscenarios[1].__iter__ = Mock(return_value=iter([]))
        subscenarios[2].status = "failed"
        subscenarios[2].__iter__ = Mock(return_value=iter([]))
        subscenarios[3].status = "skipped"
        subscenarios[3].__iter__ = Mock(return_value=iter([]))
        scenarios[0]._scenarios = subscenarios
        scenarios[1].status = "failed"
        scenarios[1].__iter__ = Mock(return_value=iter([]))
        scenarios[2].status = "skipped"
        scenarios[2].__iter__ = Mock(return_value=iter([]))
        scenarios[3].status = "passed"
        scenarios[3].__iter__ = Mock(return_value=iter([]))
        feature.status = "failed"
        feature.duration = 12.4
        feature.__iter__ = Mock(return_value=iter(scenarios))

        config = Mock()
        reporter = SummaryReporter(config)

        reporter.feature(feature)
        reporter.end()

        expected = {"passed": 2, "failed": 3, "skipped": 2, "untested": 0}

        eq_(format_summary.call_args_list[1][0], ("scenario", expected))
    def testDataExtractorInvokeFilterMethodFromTheORM(self):
        objects = Mock()
        delivery_mock = Mock()
        filter_return_value = Mock()
        filter_return_value.status = 1
        objects.filter.return_value = filter_return_value
        delivery_mock.get_automatic_correction.return_value = filter_return_value
        filter_return_value.order_by.return_value = [delivery_mock]

        practices = Mock()
        practice_mock = Mock()
        practices.all.return_value = [practice_mock]

        students = Mock()
        student_all_return_value = Mock()
        student_mock = Mock()
        student_all_return_value.order_by.return_value = [student_mock]
        students.all.return_value = student_all_return_value

        db_deliveries_extractor = DbDeliveriesExtractor()
        db_deliveries_extractor.objects = objects
        db_deliveries_extractor.students = students
        db_deliveries_extractor.practices = practices

        db_deliveries_extractor.get_data()

        objects.filter.assert_called()
    def test_redundancy_report(self):
        """
        Basic unit test of RedundancyRetentionPolicy

        Given a mock simulating a Backup with status DONE,
        the report method of the RedundancyRetentionPolicy class must mark
        it as valid
        """
        rp = self.build_redundancy_retention()
        assert isinstance(rp, RedundancyRetentionPolicy)

        # use a Mock class as BackupInfo with status to DONE
        backup_info = Mock(name="backup_info")
        backup_info.status = BackupInfo.DONE

        # instruct the get_available_backups method to return a map with
        # our mock as result and minimum_redundancy = 1
        rp.server.get_available_backups.return_value = {"test_backup": backup_info}
        rp.server.config.minimum_redundancy = 1
        # execute retention policy report
        report = rp.report()
        # check that our mock is valid for the retention policy because
        # the total number of valid backups is lower than the retention policy
        # redundancy.
        assert report == {"test_backup": BackupInfo.VALID}
    def prep_issue_request(self):
        mysock = Mock()
        mysock.gettimeout.return_value = 4242

        myresponse = Mock()
        myresponse.read.return_value = "body"
        myresponse.getheaders.return_value = "headers"
        myresponse.status = httplib.MOVED_PERMANENTLY

        myconn = Mock()
        myconn.request.return_value = None
        myconn.sock = mysock
        myconn.getresponse.return_value = myresponse
        myconn.__str__ = Mock()
        myconn.__str__.return_value = "myconn string"

        req = self.req
        req._redirect_params = Mock()
        req._redirect_params.return_value = (myconn, "url")
        req._request_str = Mock()
        req._request_str.return_value = "http://cool/cool"

        client = self.client
        client.need_login = False
        client._auto_login = False
        client._auth_cookie = False
        client.acquire_connection = Mock()
        client.acquire_connection.return_value = myconn
        client.release_connection = Mock()

        return (mysock, myresponse, myconn)
    def test_should_not_update_state_if_unaavailable(self):
        # Set
        app = NewrelicApp("1111", "777")
        headers = {"X-Api-Key": "1111"}
        url = "/v2/applications/777.json"

        # Mocks
        connection_obj = Mock()
        response_obj = Mock()
        httplib.HTTPConnection = Mock(return_value=connection_obj)

        response_obj.status = 500  # Error
        response_obj.read = Mock(return_value="")
        connection_obj.connect = Mock()
        connection_obj.request = Mock()
        connection_obj.getresponse = Mock(return_value=response_obj)

        # Assertion
        app.update_state()

        connection_obj.connect.assert_called_once()
        connection_obj.request.assert_called_once_with("GET", url, "", headers)
        connection_obj.getresponse.assert_called_once()

        self.assertFalse(app.reachable)
    def test_should_update_state_if_available(self):
        # Set
        app = NewrelicApp("1111", "777")
        headers = {"X-Api-Key": "1111"}
        url = "/v2/applications/777.json"

        # Mocks
        connection_obj = Mock()
        response_obj = Mock()
        httplib.HTTPConnection = Mock(return_value=connection_obj)

        response_obj.status = 200
        response_obj.read = Mock(return_value='{"some":"json"}')
        connection_obj.connect = Mock()
        connection_obj.request = Mock()
        connection_obj.getresponse = Mock(return_value=response_obj)

        # Assertion
        app.update_state()

        connection_obj.connect.assert_called_once()
        connection_obj.request.assert_called_once_with("GET", url, "", headers)
        connection_obj.getresponse.assert_called_once()

        self.assertEquals(app.raw_app, {"some": "json"})
        self.assertTrue(app.reachable)
    def test_recovery_window_report(self):
        """
        Basic unit test of RecoveryWindowRetentionPolicy

        Given a mock simulating a Backup with status DONE and
        the end_date not over the point of recoverability,
        the report method of the RecoveryWindowRetentionPolicy class must mark
        it as valid
        """
        rp = self.build_recovery_window_retention()
        assert isinstance(rp, RecoveryWindowRetentionPolicy)

        # use a Mock class as BackupInfo with status to DONE and end_time = now
        backup_info = Mock(name="backup_info")
        backup_info.status = BackupInfo.DONE
        backup_info.end_time = datetime.now(tzlocal())

        # instruct the get_available_backups method to return a map with
        # our mock as result and minimum_redundancy = 1
        rp.server.get_available_backups.return_value = {"test_backup": backup_info}
        rp.server.config.minimum_redundancy = 1
        # execute retention policy report
        report = rp.report()
        # check that our mock is valid for the retention policy
        assert report == {"test_backup": BackupInfo.VALID}
Example #29
0
    def test_scenario_status_is_collected_and_reported(self, format_summary, stderr):
        feature = Mock()
        scenarios = [Mock(), Mock(), Mock(), Mock(), Mock()]
        scenarios[0].status = "failed"
        scenarios[0].__iter__ = Mock(return_value=iter([]))
        scenarios[1].status = "failed"
        scenarios[1].__iter__ = Mock(return_value=iter([]))
        scenarios[2].status = "skipped"
        scenarios[2].__iter__ = Mock(return_value=iter([]))
        scenarios[3].status = "passed"
        scenarios[3].__iter__ = Mock(return_value=iter([]))
        scenarios[4].status = None
        scenarios[4].__iter__ = Mock(return_value=iter([]))
        feature.status = "failed"
        feature.duration = 12.3
        feature.__iter__ = Mock(return_value=iter(scenarios))

        config = Mock()
        reporter = SummaryReporter(config)

        reporter.feature(feature)
        reporter.end()

        expected = {"passed": 1, "failed": 2, "skipped": 2, "untested": 0}

        eq_(format_summary.call_args_list[1][0], ("scenario", expected))
Example #30
0
 def get_file(self, platform):
     file = Mock()
     file.platform_id = platform.id
     file.latest_xpi_url.return_value = "xpi.latest"
     file.get_url_path.return_value = "xpi.url"
     file.eula_url.return_value = "eula.url"
     file.status = amo.STATUS_PUBLIC
     return file