Ejemplo n.º 1
0
    def test_can_get_all_status_code(self):
        for i in range(3):
            for j in range(4):
                RequestFactory.create(
                    url='http://m.com/page-%d' % j,
                    domain_name='m.com',
                    status_code=200 + (100*j),
                )

        self.db.flush()

        response = yield self.authenticated_fetch(
            '/last-requests/status-code/'
        )

        expect(response.code).to_equal(200)

        expect(loads(response.body)).to_be_like([
            {
                u'statusCodeTitle': u'OK',
                u'statusCode': 200
            }, {
                u'statusCodeTitle': u'Multiple Choices',
                u'statusCode': 300
            }, {
                u'statusCodeTitle': u'Bad Request',
                u'statusCode': 400
            }, {
                u'statusCodeTitle': u'Internal Server Error',
                u'statusCode': 500
            }
        ])
Ejemplo n.º 2
0
    def test_voucher_update_view_for_voucher_in_set(self):
        vs = voucher.VoucherSetFactory(count=10)
        v = vs.vouchers.first()

        view = views.VoucherUpdateView.as_view()

        request = RequestFactory().get('/')
        response = view(request, pk=v.pk)
        assert response.status_code == 302
        assert response.url == reverse('dashboard:voucher-set-update', kwargs={'pk': vs.pk})
        assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == (
            'warning', "The voucher can only be edited as part of its set")

        data = {
            'code': v.code,
            'name': "New name",
            'start_datetime': v.start_datetime,
            'end_datetime': v.end_datetime,
            'usage': v.usage,
            'offers': [v.offers],
        }
        request = RequestFactory().post('/', data=data)
        response = view(request, pk=v.pk)
        assert response.status_code == 302
        assert response.url == reverse('dashboard:voucher-set-update', kwargs={'pk': vs.pk})
        assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == (
            'warning', "The voucher can only be edited as part of its set")
        v.refresh_from_db()
        assert v.name != "New name"
Ejemplo n.º 3
0
    def test_offer_delete_view_for_voucher_offer_with_vouchers(self):
        offer = ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER)
        VoucherFactory().offers.add(offer)

        view = offer_views.OfferDeleteView.as_view()

        request = RequestFactory().get('/')
        response = view(request, pk=offer.pk)
        assert response.status_code == 302
        assert response.url == reverse('dashboard:offer-detail',
                                       kwargs={'pk': offer.pk})
        assert [
            (m.level_tag, str(m.message)) for m in get_messages(request)
        ][0] == (
            'warning',
            "This offer can only be deleted if it has no vouchers attached to it"
        )

        request = RequestFactory().post('/')
        response = view(request, pk=offer.pk)
        assert response.status_code == 302
        assert response.url == reverse('dashboard:offer-detail',
                                       kwargs={'pk': offer.pk})
        assert [
            (m.level_tag, str(m.message)) for m in get_messages(request)
        ][0] == (
            'warning',
            "This offer can only be deleted if it has no vouchers attached to it"
        )
        assert ConditionalOffer.objects.exists()
Ejemplo n.º 4
0
    def test_offer_condition_view_with_custom_condition_type(self):
        range_ = RangeFactory()
        condition = create_condition(CustomConditionModel)

        request = RequestFactory().post('/',
                                        data={
                                            'range': range_.pk,
                                            'custom_condition': condition.pk,
                                        })
        request.session['offer_wizard'] = {
            self.metadata_form_kwargs_key:
            json.dumps(self.metadata_form_kwargs_session_data),
            self.metadata_obj_key:
            json.dumps(self.metadata_obj_session_data),
            self.benefit_form_kwargs_key:
            json.dumps(self.benefit_form_kwargs_session_data),
            self.benefit_obj_key:
            json.dumps(self.benefit_obj_session_data),
        }
        response = offer_views.OfferConditionView.as_view(update=True)(
            request, pk=self.offer.pk)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.url,
            reverse('dashboard:offer-restrictions',
                    kwargs={'pk': self.offer.pk}))
        self.assertJSONEqual(
            request.session['offer_wizard'][self.metadata_form_kwargs_key],
            self.metadata_form_kwargs_session_data)
        self.assertJSONEqual(
            request.session['offer_wizard'][self.metadata_obj_key],
            self.metadata_obj_session_data)
        self.assertJSONEqual(
            request.session['offer_wizard'][self.benefit_form_kwargs_key],
            self.benefit_form_kwargs_session_data)
        self.assertJSONEqual(
            request.session['offer_wizard'][self.benefit_obj_key],
            self.benefit_obj_session_data)
        self.assertJSONEqual(
            request.session['offer_wizard'][self.condition_form_kwargs_key], {
                'data': {
                    'range': range_.pk,
                    'type': '',
                    'value': None,
                    'custom_condition': str(condition.pk),
                },
            })
        self.assertJSONEqual(
            request.session['offer_wizard'][self.condition_obj_key],
            [{
                'model': 'offer.condition',
                'pk': condition.pk,
                'fields': {
                    'range': None,
                    'type': '',
                    'value': None,
                    'proxy_class': condition.proxy_class,
                }
            }])
Ejemplo n.º 5
0
    def test_offer_restrictions_view(self):
        request = RequestFactory().post('/', data={
            'priority': 0,
        })
        request.session['offer_wizard'] = {
            self.metadata_form_kwargs_key:
            json.dumps(self.metadata_form_kwargs_session_data),
            self.metadata_obj_key:
            json.dumps(self.metadata_obj_session_data),
            self.benefit_form_kwargs_key:
            json.dumps(self.benefit_form_kwargs_session_data),
            self.benefit_obj_key:
            json.dumps(self.benefit_obj_session_data),
            self.condition_form_kwargs_key:
            json.dumps(self.condition_form_kwargs_session_data),
            self.condition_obj_key:
            json.dumps(self.condition_obj_session_data),
        }
        response = offer_views.OfferRestrictionsView.as_view(update=True)(
            request, pk=self.offer.pk)

        self.offer.refresh_from_db()
        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.url,
            reverse('dashboard:offer-detail', kwargs={'pk': self.offer.pk}))
        self.assertEqual([(m.level_tag, str(m.message))
                          for m in get_messages(request)][0],
                         ('success', "Offer '%s' updated" % self.offer.name))
        self.assertEqual(request.session['offer_wizard'], {})
Ejemplo n.º 6
0
    def test_can_get_response_time_avg(self):
        self.db.query(Request).delete()

        domain = DomainFactory.create()

        avg = domain.get_response_time_avg(self.db)
        expect(avg).to_be_like(0)

        RequestFactory.create(status_code=200,
                              domain_name=domain.name,
                              response_time=0.25)
        RequestFactory.create(status_code=304,
                              domain_name=domain.name,
                              response_time=0.35)

        avg = domain.get_response_time_avg(self.db)
        expect(avg).to_be_like(0.3)

        RequestFactory.create(status_code=400,
                              domain_name=domain.name,
                              response_time=0.25)
        RequestFactory.create(status_code=403,
                              domain_name=domain.name,
                              response_time=0.35)
        RequestFactory.create(status_code=404,
                              domain_name=domain.name,
                              response_time=0.25)

        avg = domain.get_response_time_avg(self.db)
        expect(avg).to_be_like(0.3)
Ejemplo n.º 7
0
    def test_can_get_all_status_code(self):
        self.db.query(Request).delete()

        for i in range(4):
            RequestFactory.create(
                url='http://m.com/page-%d' % i,
                domain_name='m.com',
                status_code=200 + (100*i),
                completed_date=date.today() - timedelta(days=i)
            )

        status_code = Request.get_all_status_code(self.db)

        expect(status_code).to_length(4)

        expect(status_code).to_be_like([
            {
                'statusCodeTitle': 'OK',
                'statusCode': 200
            }, {
                'statusCodeTitle': 'Multiple Choices',
                'statusCode': 300
            }, {
                'statusCodeTitle': 'Bad Request',
                'statusCode': 400
            }, {
                'statusCodeTitle': 'Internal Server Error',
                'statusCode': 500
            }
        ])
Ejemplo n.º 8
0
    def test_can_get_all_status_code(self):
        self.db.query(Request).delete()

        for i in range(4):
            RequestFactory.create(
                url='http://m.com/page-%d' % i,
                domain_name='m.com',
                status_code=200 + (100*i),
                completed_date=date.today() - timedelta(days=i)
            )

        status_code = Request.get_all_status_code(self.db)

        expect(status_code).to_length(4)

        expect(status_code).to_be_like([
            {
                'statusCodeTitle': 'OK',
                'statusCode': 200
            }, {
                'statusCodeTitle': 'Multiple Choices',
                'statusCode': 300
            }, {
                'statusCodeTitle': 'Bad Request',
                'statusCode': 400
            }, {
                'statusCodeTitle': 'Internal Server Error',
                'statusCode': 500
            }
        ])
Ejemplo n.º 9
0
    def test_can_get_domains_details(self):
        self.db.query(Domain).delete()

        details = Domain.get_domains_details(self.db)

        expect(details).to_length(0)

        domain = DomainFactory.create(name='domain-1.com',
                                      url='http://domain-1.com/')
        domain2 = DomainFactory.create(name='domain-2.com',
                                       url='http://domain-2.com/')
        DomainFactory.create()

        page = PageFactory.create(domain=domain)
        page2 = PageFactory.create(domain=domain)
        page3 = PageFactory.create(domain=domain2)

        ReviewFactory.create(domain=domain,
                             page=page,
                             is_active=True,
                             number_of_violations=20)
        ReviewFactory.create(domain=domain,
                             page=page2,
                             is_active=True,
                             number_of_violations=10)
        ReviewFactory.create(domain=domain2,
                             page=page3,
                             is_active=True,
                             number_of_violations=30)

        RequestFactory.create(status_code=200,
                              domain_name=domain.name,
                              response_time=0.25)
        RequestFactory.create(status_code=304,
                              domain_name=domain.name,
                              response_time=0.35)
        RequestFactory.create(status_code=400,
                              domain_name=domain.name,
                              response_time=0.25)
        RequestFactory.create(status_code=403,
                              domain_name=domain.name,
                              response_time=0.35)
        RequestFactory.create(status_code=404,
                              domain_name=domain.name,
                              response_time=0.25)

        details = Domain.get_domains_details(self.db)

        expect(details).to_length(3)
        expect(details[0]).to_length(10)
        expect(details[0]['url']).to_equal('http://domain-1.com/')
        expect(details[0]['name']).to_equal('domain-1.com')
        expect(details[0]['violationCount']).to_equal(30)
        expect(details[0]['pageCount']).to_equal(2)
        expect(details[0]['reviewCount']).to_equal(2)
        expect(details[0]['reviewPercentage']).to_equal(100.0)
        expect(details[0]['errorPercentage']).to_equal(60.0)
        expect(details[0]['is_active']).to_be_true()
        expect(details[0]['averageResponseTime']).to_equal(0.3)
Ejemplo n.º 10
0
    def test_offer_benefit_view_with_built_in_benefit_type(self):
        range_ = RangeFactory()

        request = RequestFactory().post('/',
                                        data={
                                            'range': range_.pk,
                                            'type': Benefit.FIXED,
                                            'value': 2000,
                                        })
        request.session['offer_wizard'] = {
            self.metadata_form_kwargs_key:
            json.dumps(self.metadata_form_kwargs_session_data),
            self.metadata_obj_key:
            json.dumps(self.metadata_obj_session_data),
        }
        response = offer_views.OfferBenefitView.as_view(update=True)(
            request, pk=self.offer.pk)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.url,
            reverse('dashboard:offer-condition', kwargs={'pk': self.offer.pk}))
        self.assertJSONEqual(
            request.session['offer_wizard'][self.metadata_form_kwargs_key],
            self.metadata_form_kwargs_session_data)
        self.assertJSONEqual(
            request.session['offer_wizard'][self.metadata_obj_key],
            self.metadata_obj_session_data)
        self.assertJSONEqual(
            request.session['offer_wizard'][self.benefit_form_kwargs_key], {
                'data': {
                    'range': range_.pk,
                    'type': Benefit.FIXED,
                    'value': '2000',
                    'max_affected_items': None,
                    'custom_benefit': '',
                },
            })
        self.assertJSONEqual(
            request.session['offer_wizard'][self.benefit_obj_key],
            [{
                'model': 'offer.benefit',
                'pk': self.offer.benefit.pk,
                'fields': {
                    'range': range_.pk,
                    'type': Benefit.FIXED,
                    'value': '2000',
                    'max_affected_items': None,
                    'proxy_class': '',
                },
            }])
Ejemplo n.º 11
0
    def test_can_increment_requests_count(self):
        self.db.query(Request).delete()
        self.cache.redis.delete('requests-count')

        for i in range(2):
            RequestFactory.create()

        yield self.cache.increment_requests_count(2)
        request_count = yield self.cache.get_requests_count()
        expect(request_count).to_equal(4)

        # should get from cache
        self.cache.db = None

        request_count = yield self.cache.increment_requests_count(5)
        expect(request_count).to_equal(9)
Ejemplo n.º 12
0
    def test_offer_delete_view_for_voucher_offer_without_vouchers(self):
        offer = ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER)

        view = offer_views.OfferDeleteView.as_view()

        request = RequestFactory().get('/')
        response = view(request, pk=offer.pk)
        assert response.status_code == 200

        request = RequestFactory().post('/')
        response = view(request, pk=offer.pk)
        assert response.status_code == 302
        assert response.url == reverse('dashboard:offer-list')
        assert [(m.level_tag, str(m.message)) for m in get_messages(request)
                ][0] == ('success', "Offer deleted!")
        assert not ConditionalOffer.objects.exists()
Ejemplo n.º 13
0
    def test_get_last_requests(self):
        self.db.query(Request).delete()
        self.cache.redis.delete('requests-count')

        dt1 = datetime(2013, 11, 12, 13, 25, 27)
        dt1_timestamp = calendar.timegm(dt1.utctimetuple())

        request = RequestFactory.create(completed_date=dt1)

        response = yield self.http_client.fetch(self.get_url('/last-requests/'))

        expect(response.code).to_equal(200)

        expect(loads(response.body)).to_be_like({
            u'requestsCount': 1,
            u'requests': [{
                u'url': request.url,
                u'status_code': request.status_code,
                u'completed_date': dt1_timestamp,
                u'domain_name': request.domain_name,
                u'effective_url': request.effective_url,
                u'review_url': request.review_url,
                u'response_time': request.response_time
            }]
        })
Ejemplo n.º 14
0
 def test_default_shipping_address(self):
     user_address = factories.UserAddressFactory(
         country=self.country, user=self.user, is_default_for_shipping=True
     )
     request = RequestFactory().get(self.url, user=self.user)
     view = views.BasketView(request=request)
     self.assertEquals(view.get_default_shipping_address(), user_address)
Ejemplo n.º 15
0
    def test_can_get_requests_by_status_code(self):
        request = RequestFactory.create(
            domain_name='globo.com',
            status_code=200
        )

        loaded = Request.get_requests_by_status_code('globo.com', 200, self.db)

        expect(loaded[0].url).to_equal(request.url)
        expect(loaded[0].review_url).to_equal(request.review_url)
        expect(loaded[0].completed_date).to_equal(request.completed_date)

        invalid_domain = Request.get_requests_by_status_code(
            'g1.globo.com',
            200,
            self.db
        )
        expect(invalid_domain).to_equal([])

        invalid_code = Request.get_requests_by_status_code(
            'globo.com',
            2300,
            self.db
        )
        expect(invalid_code).to_equal([])
Ejemplo n.º 16
0
    def test_get(self):
        request = RequestFactory().get('/')

        view = views.VoucherAddView.as_view()
        response = view(request)

        self.assertEqual(response.status_code, 302)
Ejemplo n.º 17
0
    def test_can_get_domains_full_data(self):
        domains = []
        for i in range(3):
            domains.append(DomainFactory.create(name='domain-%d.com' % i))

        pages = []
        for i, domain in enumerate(domains):
            pages.append([])
            for j in range(3):
                pages[i].append(PageFactory.create(domain=domain))

        requests = reviews = []
        for i, (domain, page) in enumerate(zip(domains, pages)):
            for j in range(i + 1):
                reviews.append(
                    ReviewFactory.create(domain=domain,
                                         page=page[j],
                                         is_active=True,
                                         number_of_violations=(5 + 2 * j)))
                requests.append(
                    RequestFactory.create(status_code=200 if j %
                                          2 == 0 else 404,
                                          domain_name=domain.name,
                                          response_time=0.25 * (i + 1)))

        self.server.application.violation_definitions = {
            'key.%s' % i: {
                'title':
                'title.%s' % i,
                'category':
                'category.%s' % (i % 3),
                'key':
                Key.get_or_create(self.db, 'key.%d' % i,
                                  'category.%d' % (i % 3))
            }
            for i in range(9)
        }

        response = yield self.authenticated_fetch('/domains-details')

        expect(response.code).to_equal(200)

        full_data = loads(response.body)

        expect(full_data).to_length(3)
        expect(full_data[0].keys()).to_length(10)

        expect(map(lambda d: d['name'], full_data)).to_be_like(
            ['domain-0.com', 'domain-1.com', 'domain-2.com'])
        expect(map(lambda d: d['pageCount'], full_data)).to_be_like([3, 3, 3])
        expect(map(lambda d: d['reviewCount'],
                   full_data)).to_be_like([1, 2, 3])
        expect(map(lambda d: d['violationCount'],
                   full_data)).to_be_like([5, 12, 21])
        expect(map(lambda d: d['reviewPercentage'],
                   full_data)).to_be_like([33.33, 66.67, 100.0])
        expect(map(lambda d: d['errorPercentage'],
                   full_data)).to_be_like([0.0, 50.0, 33.33])
        expect(map(lambda d: d['averageResponseTime'],
                   full_data)).to_be_like([0.25, 0.5, 0.75])
Ejemplo n.º 18
0
    def test_can_get_requests_by_status_code(self):
        request = RequestFactory.create(
            domain_name='globo.com',
            status_code=200
        )

        loaded = Request.get_requests_by_status_code('globo.com', 200, self.db)

        expect(loaded[0].url).to_equal(request.url)
        expect(loaded[0].review_url).to_equal(request.review_url)
        expect(loaded[0].completed_date).to_equal(request.completed_date)

        invalid_domain = Request.get_requests_by_status_code(
            'g1.globo.com',
            200,
            self.db
        )
        expect(invalid_domain).to_equal([])

        invalid_code = Request.get_requests_by_status_code(
            'globo.com',
            2300,
            self.db
        )
        expect(invalid_code).to_equal([])
Ejemplo n.º 19
0
    def test_offer_condition_view_with_built_in_condition_type(self):
        range_ = RangeFactory()

        request = RequestFactory().post('/',
                                        data={
                                            'range': range_.pk,
                                            'type': Condition.COUNT,
                                            'value': 10,
                                        })
        request.session['offer_wizard'] = {
            'metadata': json.dumps(self.metadata_form_kwargs_session_data),
            'metadata_obj': json.dumps(self.metadata_obj_session_data),
            'benefit': json.dumps(self.benefit_form_kwargs_session_data),
            'benefit_obj': json.dumps(self.benefit_obj_session_data),
        }
        response = offer_views.OfferConditionView.as_view()(request)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, reverse('dashboard:offer-restrictions'))
        self.assertJSONEqual(request.session['offer_wizard']['metadata'],
                             self.metadata_form_kwargs_session_data)
        self.assertJSONEqual(request.session['offer_wizard']['metadata_obj'],
                             self.metadata_obj_session_data)
        self.assertJSONEqual(request.session['offer_wizard']['benefit'],
                             self.benefit_form_kwargs_session_data)
        self.assertJSONEqual(request.session['offer_wizard']['benefit_obj'],
                             self.benefit_obj_session_data)
        self.assertJSONEqual(
            request.session['offer_wizard']['condition'], {
                'data': {
                    'range': range_.pk,
                    'type': Condition.COUNT,
                    'value': '10',
                    'custom_condition': '',
                },
            })
        self.assertJSONEqual(request.session['offer_wizard']['condition_obj'],
                             [{
                                 'model': 'offer.condition',
                                 'pk': None,
                                 'fields': {
                                     'range': range_.pk,
                                     'type': Condition.COUNT,
                                     'value': '10',
                                     'proxy_class': None,
                                 },
                             }])
Ejemplo n.º 20
0
    def test_can_get_requests_count(self):
        self.db.query(Request).delete()

        key = 'requests-count'
        self.cache.redis.delete(key)

        for i in range(2):
            RequestFactory.create()

        request_count = yield self.cache.get_requests_count()
        expect(request_count).to_equal(2)

        # should get from cache
        self.cache.db = None

        request_count = yield self.cache.get_requests_count()
        expect(request_count).to_equal(2)
Ejemplo n.º 21
0
    def test_can_remove_old_requests(self):
        self.db.query(Request).delete()

        config = Config()
        config.DAYS_TO_KEEP_REQUESTS = 1

        for i in range(4):
            RequestFactory.create(
                url='http://m.com/page-%d' % i,
                domain_name='m.com',
                status_code=200,
                completed_date=date.today() - timedelta(days=i)
            )

        Request.delete_old_requests(self.db, config)

        requests = self.db.query(Request).all()
        expect(requests).to_length(1)
Ejemplo n.º 22
0
    def test_can_remove_old_requests(self):
        self.db.query(Request).delete()

        config = Config()
        config.DAYS_TO_KEEP_REQUESTS = 1

        for i in range(4):
            RequestFactory.create(
                url='http://m.com/page-%d' % i,
                domain_name='m.com',
                status_code=200,
                completed_date=date.today() - timedelta(days=i)
            )

        Request.delete_old_requests(self.db, config)

        requests = self.db.query(Request).all()
        expect(requests).to_length(1)
Ejemplo n.º 23
0
    def test_can_get_status_code_info(self):
        request = RequestFactory.create(domain_name='g1.globo.com')

        loaded = Request.get_status_code_info('g1.globo.com', self.db)

        expect(loaded[0].get('code')).to_equal(request.status_code)
        expect(loaded[0].get('total')).to_equal(1)

        invalid_domain = Request.get_status_code_info('g2.globo.com', self.db)
        expect(invalid_domain).to_equal([])
Ejemplo n.º 24
0
    def test_can_increment_requests_count(self):
        self.db.query(Request).delete()

        key = 'requests-count'
        self.sync_cache.redis.delete(key)

        for i in range(5):
            RequestFactory.create()

        self.sync_cache.increment_requests_count(4)
        page_count = self.sync_cache.redis.get(key)
        expect(page_count).to_equal('9')

        # should get from cache
        self.sync_cache.db = None

        self.sync_cache.increment_requests_count(10)
        page_count = self.sync_cache.redis.get(key)
        expect(page_count).to_equal('19')
Ejemplo n.º 25
0
    def test_can_get_status_code_info(self):
        request = RequestFactory.create(domain_name='g1.globo.com')

        loaded = Request.get_status_code_info('g1.globo.com', self.db)

        expect(loaded[0].get('code')).to_equal(request.status_code)
        expect(loaded[0].get('total')).to_equal(1)

        invalid_domain = Request.get_status_code_info('g2.globo.com', self.db)
        expect(invalid_domain).to_equal([])
Ejemplo n.º 26
0
    def test_get_last_requests(self):
        self.db.query(Request).delete()

        dt1 = datetime(2013, 11, 12)
        dt1_timestamp = calendar.timegm(dt1.utctimetuple())

        domain1 = DomainFactory.create()
        domain2 = DomainFactory.create()
        request = RequestFactory.create(
            domain_name=domain1.name, completed_date=dt1
        )

        response = yield self.authenticated_fetch('/last-requests/')

        expect(response.code).to_equal(200)

        expect(loads(response.body)).to_be_like({
            u'requests': [{
                u'url': request.url,
                u'status_code': request.status_code,
                u'completed_date': dt1_timestamp,
                u'domain_name': request.domain_name,
                u'effective_url': request.effective_url,
                u'review_url': request.review_url,
                u'response_time': request.response_time
            }]
        })

        request = RequestFactory.create(domain_name=domain2.name,
                                        completed_date=dt1)

        response = yield self.authenticated_fetch('/last-requests/')
        expect(response.code).to_equal(200)
        expect(len(loads(response.body)['requests'])).to_be_like(2)

        response = yield self.authenticated_fetch(
            '/last-requests/?domain_filter=%s' % domain2.name
        )
        expect(response.code).to_equal(200)
        response_body = loads(response.body)
        expect(len(response_body['requests'])).to_be_like(1)
        expect(response_body['requests'][0]['domain_name']).to_be_like(domain2.name)
Ejemplo n.º 27
0
    def test_get_last_requests_filter_by_staus_code(self):
        for i in range(3):
            RequestFactory.create(
                status_code=200,
                domain_name='globo.com'
            )
            RequestFactory.create(
                status_code=404,
                domain_name='g1.globo.com'
            )

        response = yield self.authenticated_fetch(
            '/last-requests/?status_code_filter=200'
        )

        expect(response.code).to_equal(200)

        response_body = loads(response.body)
        expect(response_body['requests']).to_length(3)
        expect(response_body['requests'][0]['domain_name']).to_be_like('globo.com')
Ejemplo n.º 28
0
    def test_can_get_response_time_avg(self):
        self.db.query(Request).delete()

        domain = DomainFactory.create()

        avg = domain.get_response_time_avg(self.db)
        expect(avg).to_be_like(0)

        RequestFactory.create(status_code=200, domain_name=domain.name, response_time=0.25)
        RequestFactory.create(status_code=304, domain_name=domain.name, response_time=0.35)

        avg = domain.get_response_time_avg(self.db)
        expect(avg).to_be_like(0.3)

        RequestFactory.create(status_code=400, domain_name=domain.name, response_time=0.25)
        RequestFactory.create(status_code=403, domain_name=domain.name, response_time=0.35)
        RequestFactory.create(status_code=404, domain_name=domain.name, response_time=0.25)

        avg = domain.get_response_time_avg(self.db)
        expect(avg).to_be_like(0.3)
Ejemplo n.º 29
0
    def test_can_get_bad_request_count(self):
        self.db.query(Request).delete()

        domain = DomainFactory.create()

        bad = domain.get_bad_request_count(self.db)
        expect(bad).to_equal(0)

        RequestFactory.create(status_code=200, domain_name=domain.name)
        RequestFactory.create(status_code=304, domain_name=domain.name)

        bad = domain.get_bad_request_count(self.db)
        expect(bad).to_equal(0)

        RequestFactory.create(status_code=400, domain_name=domain.name)
        RequestFactory.create(status_code=403, domain_name=domain.name)
        RequestFactory.create(status_code=404, domain_name=domain.name)

        bad = domain.get_bad_request_count(self.db)
        expect(bad).to_equal(3)
Ejemplo n.º 30
0
 def test_voucher_delete_view_for_voucher_in_set(self):
     vs = voucher.VoucherSetFactory(count=10)
     assert Voucher.objects.count() == 10
     request = RequestFactory().post('/')
     response = views.VoucherDeleteView.as_view()(request, pk=vs.vouchers.first().pk)
     vs.refresh_from_db()
     assert vs.count == 9  # "count" is updated
     assert Voucher.objects.count() == 9
     assert response.status_code == 302
     assert response.url == reverse('dashboard:voucher-set-detail', kwargs={'pk': vs.pk})
     assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == ('warning', "Voucher deleted")
Ejemplo n.º 31
0
    def test_can_get_bad_request_count(self):
        self.db.query(Request).delete()

        domain = DomainFactory.create()

        bad = domain.get_bad_request_count(self.db)
        expect(bad).to_equal(0)

        RequestFactory.create(status_code=200, domain_name=domain.name)
        RequestFactory.create(status_code=304, domain_name=domain.name)

        bad = domain.get_bad_request_count(self.db)
        expect(bad).to_equal(0)

        RequestFactory.create(status_code=400, domain_name=domain.name)
        RequestFactory.create(status_code=403, domain_name=domain.name)
        RequestFactory.create(status_code=404, domain_name=domain.name)

        bad = domain.get_bad_request_count(self.db)
        expect(bad).to_equal(3)
Ejemplo n.º 32
0
 def test_voucher_set_delete_view(self):
     vs = voucher.VoucherSetFactory(count=10)
     assert VoucherSet.objects.count() == 1
     assert Voucher.objects.count() == 10
     request = RequestFactory().post('/')
     response = views.VoucherSetDeleteView.as_view()(request, pk=vs.pk)
     assert VoucherSet.objects.count() == 0
     assert Voucher.objects.count() == 0
     assert response.status_code == 302
     assert response.url == reverse('dashboard:voucher-set-list')
     assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == ('warning', "Voucher set deleted")
Ejemplo n.º 33
0
    def test_offer_benefit_view_with_custom_benefit_type(self):
        benefit = create_benefit(CustomBenefitModel)

        request = RequestFactory().post('/',
                                        data={
                                            'custom_benefit': benefit.pk,
                                        })
        request.session['offer_wizard'] = {
            'metadata': json.dumps(self.metadata_form_kwargs_session_data),
            'metadata_obj': json.dumps(self.metadata_obj_session_data),
        }
        response = offer_views.OfferBenefitView.as_view()(request)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, reverse('dashboard:offer-condition'))
        self.assertJSONEqual(request.session['offer_wizard']['metadata'],
                             self.metadata_form_kwargs_session_data)
        self.assertJSONEqual(request.session['offer_wizard']['metadata_obj'],
                             self.metadata_obj_session_data)
        self.assertJSONEqual(
            request.session['offer_wizard']['benefit'], {
                'data': {
                    'range': None,
                    'type': '',
                    'value': None,
                    'max_affected_items': None,
                    'custom_benefit': str(benefit.pk),
                },
            })
        self.assertJSONEqual(request.session['offer_wizard']['benefit_obj'],
                             [{
                                 'model': 'offer.benefit',
                                 'pk': benefit.pk,
                                 'fields': {
                                     'range': None,
                                     'type': '',
                                     'value': None,
                                     'max_affected_items': None,
                                     'proxy_class': benefit.proxy_class,
                                 }
                             }])
Ejemplo n.º 34
0
    def test_can_get_response_time_avg_for_domain(self):
        self.db.query(Request).delete()
        self.db.query(Domain).delete()
        DomainFactory.create(url='http://globo.com', name='globo.com')

        key = 'globo.com-response-time-avg'
        self.cache.redis.delete(key)

        RequestFactory.create(status_code=200, domain_name='globo.com', response_time=0.25)
        RequestFactory.create(status_code=304, domain_name='globo.com', response_time=0.35)
        RequestFactory.create(status_code=400, domain_name='globo.com', response_time=0.25)
        RequestFactory.create(status_code=403, domain_name='globo.com', response_time=0.35)
        RequestFactory.create(status_code=404, domain_name='globo.com', response_time=0.25)

        avg = yield self.cache.get_response_time_avg('globo.com')
        expect(avg).to_be_like(0.3)

        self.cache.db = None

        avg = yield self.cache.get_response_time_avg('globo.com')
        expect(avg).to_be_like(0.3)
Ejemplo n.º 35
0
    def test_can_convert_request_to_dict(self):
        request = RequestFactory.create()

        request_dict = request.to_dict()

        expect(request_dict['domain_name']).to_equal(str(request.domain_name))
        expect(request_dict['url']).to_equal(request.url)
        expect(request_dict['effective_url']).to_equal(request.effective_url)
        expect(request_dict['status_code']).to_equal(request.status_code)
        expect(request_dict['response_time']).to_equal(request.response_time)
        expect(request_dict['completed_date']).to_equal(request.completed_date)
        expect(request_dict['review_url']).to_equal(request.review_url)
Ejemplo n.º 36
0
    def test_can_convert_request_to_dict(self):
        request = RequestFactory.create()

        request_dict = request.to_dict()

        expect(request_dict['domain_name']).to_equal(str(request.domain_name))
        expect(request_dict['url']).to_equal(request.url)
        expect(request_dict['effective_url']).to_equal(request.effective_url)
        expect(request_dict['status_code']).to_equal(request.status_code)
        expect(request_dict['response_time']).to_equal(request.response_time)
        expect(request_dict['completed_date']).to_equal(request.completed_date)
        expect(request_dict['review_url']).to_equal(request.review_url)
Ejemplo n.º 37
0
    def test_can_get_bad_request_count_for_domain(self):
        self.db.query(Request).delete()
        self.db.query(Domain).delete()
        DomainFactory.create(url='http://globo.com', name='globo.com')

        key = 'globo.com-bad-request-count'
        self.cache.redis.delete(key)

        RequestFactory.create(status_code=200, domain_name='globo.com')
        RequestFactory.create(status_code=304, domain_name='globo.com')
        RequestFactory.create(status_code=400, domain_name='globo.com')
        RequestFactory.create(status_code=403, domain_name='globo.com')
        RequestFactory.create(status_code=404, domain_name='globo.com')

        bad = yield self.cache.get_bad_request_count('globo.com')
        expect(bad).to_equal(3)

        self.cache.db = None

        bad = yield self.cache.get_bad_request_count('globo.com')
        expect(bad).to_equal(3)
Ejemplo n.º 38
0
    def test_can_get_domains_full_data(self):
        domains = []
        for i in xrange(3):
            domains.append(DomainFactory.create(name='domain-%d.com' % i))

        pages = []
        for i, domain in enumerate(domains):
            pages.append([])
            for j in xrange(3):
                pages[i].append(PageFactory.create(domain=domain))

        requests = reviews = []
        for i, (domain, page) in enumerate(zip(domains, pages)):
            for j in xrange(i + 1):
                reviews.append(ReviewFactory.create(
                    domain=domain,
                    page=page[j],
                    is_active=True,
                    number_of_violations=(5 + 2 * j)
                ))
                requests.append(RequestFactory.create(
                    status_code=200 if j % 2 == 0 else 404,
                    domain_name=domain.name,
                    response_time=0.25 * (i + 1)
                ))

        self.server.application.violation_definitions = {
            'key.%s' % i: {
                'title': 'title.%s' % i,
                'category': 'category.%s' % (i % 3),
                'key': Key.get_or_create(self.db, 'key.%d' % i, 'category.%d' % (i % 3))
            } for i in xrange(9)
        }

        response = yield self.http_client.fetch(
            self.get_url('/domains-details')
        )

        expect(response.code).to_equal(200)

        full_data = loads(response.body)

        expect(full_data).to_length(3)
        expect(full_data[0].keys()).to_length(10)

        expect(map(lambda d: d['name'], full_data)).to_be_like(['domain-0.com', 'domain-1.com', 'domain-2.com'])
        expect(map(lambda d: d['pageCount'], full_data)).to_be_like([3, 3, 3])
        expect(map(lambda d: d['reviewCount'], full_data)).to_be_like([1, 2, 3])
        expect(map(lambda d: d['violationCount'], full_data)).to_be_like([5, 12, 21])
        expect(map(lambda d: d['reviewPercentage'], full_data)).to_be_like([33.33, 66.67, 100.0])
        expect(map(lambda d: d['errorPercentage'], full_data)).to_be_like([0.0, 50.0, 33.33])
        expect(map(lambda d: d['averageResponseTime'], full_data)).to_be_like([0.25, 0.5, 0.75])
Ejemplo n.º 39
0
 def test_voucher_delete_view(self):
     v = voucher.VoucherFactory()
     v.offers.add(ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER))
     assert Voucher.objects.count() == 1
     assert ConditionalOffer.objects.count() == 1
     request = RequestFactory().post('/')
     response = views.VoucherDeleteView.as_view()(request, pk=v.pk)
     assert Voucher.objects.count() == 0
     # Related offer is not deleted
     assert ConditionalOffer.objects.count() == 1
     assert response.status_code == 302
     assert response.url == reverse('dashboard:voucher-list')
     assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == ('warning', "Voucher deleted")
Ejemplo n.º 40
0
    def test_post_with_missing_voucher(self):
        """ If the voucher is missing, verify the view queues a message and redirects. """
        pk = '12345'
        view = views.VoucherRemoveView.as_view()
        request = RequestFactory().post('/')
        request.basket.save()
        response = view(request, pk=pk)

        self.assertEqual(response.status_code, 302)

        actual = list(get_messages(request))[-1].message
        expected = "No voucher found with id '{}'".format(pk)
        self.assertEqual(actual, expected)
Ejemplo n.º 41
0
    def test_can_create_request(self):
        request = RequestFactory.create()

        expect(str(request)).to_equal('http://g1.globo.com (301)')

        expect(request.id).not_to_be_null()
        expect(request.domain_name).to_equal('g1.globo.com')
        expect(request.url).to_equal('http://g1.globo.com')
        expect(request.effective_url).to_equal('http://g1.globo.com/')
        expect(request.status_code).to_equal(301)
        expect(request.response_time).to_equal(0.23)
        expect(request.completed_date).to_equal(date(2013, 2, 12))
        expect(request.review_url).to_equal('http://globo.com/')
Ejemplo n.º 42
0
    def test_can_create_request(self):
        request = RequestFactory.create()

        expect(str(request)).to_equal('http://g1.globo.com (301)')

        expect(request.id).not_to_be_null()
        expect(request.domain_name).to_equal('g1.globo.com')
        expect(request.url).to_equal('http://g1.globo.com')
        expect(request.effective_url).to_equal('http://g1.globo.com/')
        expect(request.status_code).to_equal(301)
        expect(request.response_time).to_equal(0.23)
        expect(request.completed_date).to_equal(date(2013, 2, 12))
        expect(request.review_url).to_equal('http://globo.com/')
Ejemplo n.º 43
0
    def test_offer_meta_data_view(self):
        request = RequestFactory().post('/',
                                        data={
                                            'name': 'Test offer',
                                            'description': 'Test description',
                                            'offer_type':
                                            ConditionalOffer.VOUCHER,
                                        })
        response = offer_views.OfferMetaDataView.as_view(update=True)(
            request, pk=self.offer.pk)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.url,
            reverse('dashboard:offer-benefit', kwargs={'pk': self.offer.pk}))
        self.assertJSONEqual(
            request.session['offer_wizard'][self.metadata_form_kwargs_key], {
                'data': {
                    'name': 'Test offer',
                    'description': 'Test description',
                    'offer_type': ConditionalOffer.VOUCHER,
                },
            })
        self.assertJSONEqual(
            request.session['offer_wizard'][self.metadata_obj_key],
            [{
                'model': 'offer.conditionaloffer',
                'pk': self.offer.pk,
                'fields': {
                    'name': 'Test offer',
                    'slug': self.offer.slug,
                    'description': 'Test description',
                    'offer_type': ConditionalOffer.VOUCHER,
                    'exclusive': True,
                    'status': ConditionalOffer.OPEN,
                    'condition': self.offer.condition.pk,
                    'benefit': self.offer.benefit.pk,
                    'priority': 0,
                    'start_datetime': None,
                    'end_datetime': None,
                    'max_global_applications': None,
                    'max_user_applications': None,
                    'max_basket_applications': None,
                    'max_discount': None,
                    'total_discount': '0.00',
                    'num_applications': 0,
                    'num_orders': 0,
                    'redirect_url': '',
                    'date_created': '2021-04-23T14:00:00Z',
                },
            }])
Ejemplo n.º 44
0
    def test_can_get_domains_details(self):
        self.db.query(Domain).delete()

        details = Domain.get_domains_details(self.db)

        expect(details).to_length(0)

        domain = DomainFactory.create(name='domain-1.com', url='http://domain-1.com/')
        domain2 = DomainFactory.create(name='domain-2.com', url='http://domain-2.com/')
        DomainFactory.create()

        page = PageFactory.create(domain=domain)
        page2 = PageFactory.create(domain=domain)
        page3 = PageFactory.create(domain=domain2)

        ReviewFactory.create(domain=domain, page=page, is_active=True, number_of_violations=20)
        ReviewFactory.create(domain=domain, page=page2, is_active=True, number_of_violations=10)
        ReviewFactory.create(domain=domain2, page=page3, is_active=True, number_of_violations=30)

        RequestFactory.create(status_code=200, domain_name=domain.name, response_time=0.25)
        RequestFactory.create(status_code=304, domain_name=domain.name, response_time=0.35)
        RequestFactory.create(status_code=400, domain_name=domain.name, response_time=0.25)
        RequestFactory.create(status_code=403, domain_name=domain.name, response_time=0.35)
        RequestFactory.create(status_code=404, domain_name=domain.name, response_time=0.25)

        details = Domain.get_domains_details(self.db)

        expect(details).to_length(3)
        expect(details[0]).to_length(10)
        expect(details[0]['url']).to_equal('http://domain-1.com/')
        expect(details[0]['name']).to_equal('domain-1.com')
        expect(details[0]['violationCount']).to_equal(30)
        expect(details[0]['pageCount']).to_equal(2)
        expect(details[0]['reviewCount']).to_equal(2)
        expect(details[0]['reviewPercentage']).to_equal(100.0)
        expect(details[0]['errorPercentage']).to_equal(60.0)
        expect(details[0]['is_active']).to_be_true()
        expect(details[0]['averageResponseTime']).to_equal(0.3)
Ejemplo n.º 45
0
    def test_offer_restrictions_view(self):
        request = RequestFactory().post('/', data={
            'priority': 0,
        })
        request.session['offer_wizard'] = {
            'metadata': json.dumps(self.metadata_form_kwargs_session_data),
            'metadata_obj': json.dumps(self.metadata_obj_session_data),
            'benefit': json.dumps(self.benefit_form_kwargs_session_data),
            'benefit_obj': json.dumps(self.benefit_obj_session_data),
            'condition': json.dumps(self.condition_form_kwargs_session_data),
            'condition_obj': json.dumps(self.condition_obj_session_data),
        }
        response = offer_views.OfferRestrictionsView.as_view()(request)

        offer = ConditionalOffer.objects.get()
        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.url,
            reverse('dashboard:offer-detail', kwargs={'pk': offer.pk}))
        self.assertEqual([(m.level_tag, str(m.message))
                          for m in get_messages(request)][0],
                         ('success', "Offer '%s' created!" % offer.name))
        self.assertEqual(request.session['offer_wizard'], {})
Ejemplo n.º 46
0
    def test_post_valid(self):
        voucher = VoucherFactory(num_basket_additions=5)

        data = {'code': voucher.code}
        request = RequestFactory().post('/', data=data)
        request.basket.save()
        request.basket.vouchers.add(voucher)

        view = views.VoucherRemoveView.as_view()
        response = view(request, pk=voucher.pk)
        self.assertEqual(response.status_code, 302)

        voucher = voucher.__class__.objects.get(pk=voucher.pk)
        self.assertEqual(voucher.num_basket_additions, 4)
Ejemplo n.º 47
0
    def test_can_get_requests_by_status_count(self):
        for i in range(4):
            RequestFactory.create(domain_name='globo.com', status_code=200)

        total = Request.get_requests_by_status_count(
            'globo.com',
            200,
            self.db
        )
        expect(total).to_equal(4)

        invalid_domain = Request.get_requests_by_status_code(
            'g1.globo.com',
            200,
            self.db
        )
        expect(invalid_domain).to_equal([])

        invalid_code = Request.get_requests_by_status_code(
            'globo.com',
            2300,
            self.db
        )
        expect(invalid_code).to_equal([])
Ejemplo n.º 48
0
    def test_can_get_requests_count_by_status(self):
        utcnow = datetime.utcnow()

        DomainFactory.create(name='globo.com')
        DomainFactory.create(name='globoesporte.com')
        DomainFactory.create(name='domain3.com')

        for i in range(3):
            RequestFactory.create(
                status_code=200,
                completed_date=utcnow.date() - timedelta(days=i),
                domain_name='globo.com'
            )
            RequestFactory.create(
                status_code=404,
                completed_date=utcnow.date() - timedelta(days=i),
                domain_name='globo.com'
            )
            RequestFactory.create(
                status_code=404,
                completed_date=utcnow.date() - timedelta(days=i),
                domain_name='globoesporte.com'
            )
            RequestFactory.create(
                status_code=599,
                completed_date=utcnow.date() - timedelta(days=i),
            )

        self.db.flush()

        counts = Request.get_requests_count_by_status(self.db)
        expect(counts).to_equal({
            '_all': [(200, 3), (404, 6)],
             u'globo.com': [(200, 3), (404, 3)],
             u'domain3.com': [],
             u'globoesporte.com': [(404, 3)]
        })
Ejemplo n.º 49
0
    def test_get_requests_in_last_day(self):
        utcnow = datetime.utcnow().date()

        for i in range(3):
            RequestFactory.create(
                status_code=200,
                completed_date=utcnow - timedelta(days=1)
            )
            RequestFactory.create(
                status_code=404,
                completed_date=utcnow - timedelta(days=i)
            )
            RequestFactory.create(
                status_code=599,
                completed_date=utcnow - timedelta(days=i + 1)
            )

        self.db.flush()

        response = yield self.http_client.fetch(self.get_url('/requests-in-last-day/'))

        expect(response.code).to_equal(200)

        expect(loads(response.body)).to_be_like([
            {
                'statusCode': 200,
                'statusCodeTitle': 'OK',
                'count': 3
            }, {
                'statusCode': 404,
                'statusCodeTitle': 'Not Found',
                'count': 2
            }, {
                'statusCode': 599,
                'statusCodeTitle': 'Tornado Timeout',
                'count': 1
            }
        ])
Ejemplo n.º 50
0
    def test_can_get_latest_failed_responses(self):
        self.db.query(Request).delete()

        utcnow = datetime.utcnow()

        DomainFactory.create(name='globo.com')
        DomainFactory.create(name='globoesporte.com')
        DomainFactory.create(name='domain3.com')

        for i in range(3):
            RequestFactory.create(
                status_code=200,
                completed_date=utcnow.date() - timedelta(days=i),
                domain_name='globo.com'
            )
            RequestFactory.create(
                status_code=404,
                completed_date=utcnow.date() - timedelta(days=i),
                domain_name='globo.com'
            )
            RequestFactory.create(
                status_code=404,
                completed_date=utcnow.date() - timedelta(days=i),
                domain_name='globoesporte.com'
            )
            RequestFactory.create(
                status_code=599,
                completed_date=utcnow.date() - timedelta(days=i),
                domain_name='g1.globo.com'
            )

        self.db.flush()

        response = yield self.authenticated_fetch(
            '/last-requests/failed-responses/'
        )
        expect(response.code).to_equal(200)
        expect(loads(response.body)).to_be_like([
            {u'count': 3, u'statusCodeTitle': u'OK', u'statusCode': 200},
            {u'count': 6, u'statusCodeTitle': u'Not Found', u'statusCode': 404}
        ])

        response = yield self.authenticated_fetch(
            '/last-requests/failed-responses/?domain_filter=globo.com'
        )
        expect(response.code).to_equal(200)
        expect(loads(response.body)).to_be_like([
            {u'count': 3, u'statusCodeTitle': u'OK', u'statusCode': 200},
            {u'count': 3, u'statusCodeTitle': u'Not Found', u'statusCode': 404}
        ])

        response = yield self.authenticated_fetch(
            '/last-requests/failed-responses/?domain_filter=globoesporte.com'
        )
        expect(response.code).to_equal(200)
        expect(loads(response.body)).to_be_like([
            {u'count': 3, u'statusCodeTitle': u'Not Found', u'statusCode': 404}
        ])

        response = yield self.authenticated_fetch(
            '/last-requests/failed-responses/?domain_filter=g1.globo.com'
        )
        expect(response.code).to_equal(200)
        expect(loads(response.body)).to_be_like([])

        response = yield self.authenticated_fetch(
            '/last-requests/failed-responses/?domain_filter=domain3.com'
        )
        expect(response.code).to_equal(200)
        expect(loads(response.body)).to_be_like([])