Beispiel #1
0
def test_edit_publishersets(client, auth_app, publisherset_db):
    '''
    Edits existing publisher by removing one of the TargetValue
    '''

    client.login(username=user['username'],
                 password=user['password'])

    _, sets = get_resource(client, PUBLISHERS_SET_URL)

    current_count = PublisherSet.objects.count()

    for set_element in sets['objects']:
        _, full_set = get_resource(client, set_element['resource_uri'])

        all_ids = full_set['targetvalues_ids']

        full_set['targetvalues_ids'] = full_set['targetvalues_ids'][:1]

        res = client.put(set_element['resource_uri'],
                         data=json.dumps(full_set),
                         content_type='application/json')

        # this should not change! as put requests should only edit resource.
        assert current_count == PublisherSet.objects.count()
        # this assert is placed here to make sure our api is secured against
        # this strange bug in tastypie

        edited_set = json.loads(res.content)

        assert not edited_set['targetvalues_ids'] == all_ids
Beispiel #2
0
def test_add_flash_creative(client, flashfile):
    '''adding new creative'''

    url = '/api/storage/creative/'

    client.login(username=users[0]['username'], password=users[0]['password'])

    _, response = get_resource(client, url)

    assert len(response['objects']) == 2

    new_creative = {
        'type': 'Flash',
        'name': 'Awsome flash file',
        'api_data': flashfile
    }

    res = client.post(url,
                      data=json.dumps(new_creative),
                      content_type='application/json')
    response = json.loads(res.content)

    assert response['width'] == 300
    assert response['height'] == 250
    assert response['type'] == 'Flash'

    _, response = get_resource(client, url)
    assert len(response['objects']) == 3
Beispiel #3
0
def test_delete_creative(client):
    '''delete creative'''

    url = '/api/storage/creative/'

    client.login(username=users[0]['username'], password=users[0]['password'])

    account = Account.objects.get(name=default_account[0]['name'])

    creatives = Creative.objects_visible.filter(owner=account)

    _, response = get_resource(client, url)

    assert len(creatives) == 2
    assert len(response['objects']) == 2

    object_to_delete = response['objects'][0]

    res = client.delete(object_to_delete['resource_uri'])

    assert res.status_code == 204
    assert not res.content

    status, _ = get_resource(client, object_to_delete['resource_uri'])
    assert status == 404

    creatives = Creative.objects_visible.filter(owner=account)

    _, response = get_resource(client, url)

    assert len(creatives) == 1
    assert len(response['objects']) == 1
Beispiel #4
0
def test_add_creative(client, imagefile, creative_type, is_valid):
    '''adding new creative'''

    url = '/api/storage/creative/'

    client.login(username=users[0]['username'], password=users[0]['password'])

    _, response = get_resource(client, url)

    assert len(response['objects']) == 2

    new_creative = {
        'type': creative_type,
        'name': 'Awsome image',
        'api_data': imagefile
    }

    res = client.post(url,
                      data=json.dumps(new_creative),
                      content_type='application/json')

    response = json.loads(res.content)

    if is_valid:
        assert response['width'] == 200
        assert response['height'] == 200
        assert response['type'] == 'Image'

        _, response = get_resource(client, url)
        assert len(response['objects']) == 3
    else:
        assert res.status_code == 400
        assert response[
            'error'] == "[u'You cannot create creative without a type.']"
Beispiel #5
0
def test_creatives_view(client):
    '''test for one creative view'''

    url = '/api/storage/creative/'

    client.login(username=users[0]['username'], password=users[0]['password'])

    account = Account.objects.get(name=default_account[0]['name'])

    creatives = Creative.objects_visible.filter(owner=account)

    _, response = get_resource(client, url)

    for creative in creatives:
        elements = [
            rc for rc in response['objects'] if rc['id'] == creative.id
        ]
        assert elements

        # checking if type is equal substracted Creative class name
        assert elements[0]['type'] == creative.__class__.__name__[8:]

        status, creative_resource = get_resource(client,
                                                 elements[0]['resource_uri'])

        assert status == 200
        assert creative_resource == elements[0]
Beispiel #6
0
def test_publishers_filter_by_network(client):
    publishers_targetvalue = PublisherTargetValue.objects.representants()

    networks = []
    publishers = []
    for publisher in publishers_targetvalue:
        if publisher.key == dimensions.network:
            networks.append(publisher)
        else:
            publishers.append(publisher)

    assert networks

    for network in networks:
        filtered_publishers = []
        # lets filter those with given inventory and network id only:
        for publisher in publishers:
            if publisher.network_id == network.network_id and \
                            publisher.inventory_key == network.inventory_key:
                filtered_publishers.append(publisher)

        network_filter_url = '{0}?network_id={1}&inventory={2}'.format(
            PUBLISHERS_LIST_URL,
            network.network_id,
            network.inventory_key
        )

        _, network_data = get_resource(client, network_filter_url)
        assert network_data['meta']['total_count'] == len(filtered_publishers)

        for publisher in network_data['objects']:
            check_data(publisher)

        for filtered_publisher in filtered_publishers:
            publisher_filter_url = '{0}?publisher_id={1}-{2}&inventory={3}' \
                .format(
                PUBLISHERS_LIST_URL,
                filtered_publisher.network_id,
                filtered_publisher.id,
                filtered_publisher.inventory_key
            )

            _, data = get_resource(client, publisher_filter_url)
            # exact match
            assert data['meta']['total_count'] == 1

            assert data['objects'][0] in network_data['objects']

            check_data(data['objects'][0])
Beispiel #7
0
def test_creatives_list(client, user, creatives_count):
    '''
    Check list creatives, if we get creatives assigned for given user
    '''

    list_url = '/api/storage/creative/'

    status_code, _ = get_resource(client, list_url)
    assert status_code == 401

    client.login(username=user['username'], password=user['password'])

    status_code, content = get_resource(client, list_url)
    assert status_code == 200

    assert content['meta']['total_count'] == creatives_count
    assert len(content['objects']) == creatives_count
Beispiel #8
0
def test_publishers_filter_by_name(client, name, count, contains):
    filter_url = '{0}?name={1}'.format(PUBLISHERS_LIST_URL, name)

    _, data = get_resource(client, filter_url)

    assert data['meta']['total_count'] == count
    # exact match should be higher
    if contains:
        assert name in data['objects'][contains - 1]['name']
Beispiel #9
0
def test_edit_creative(client, imagefile):
    '''updating existing creative'''

    url = '/api/storage/creative/'

    client.login(username=users[0]['username'], password=users[0]['password'])

    _, response = get_resource(client, url)

    # we have two creatives
    assert len(response['objects']) == 2

    # we take one to edit
    original_creative = response['objects'][0]
    db_object = Creative.objects_visible.filter(id=original_creative['id'])[0]

    # we change everything except id
    edited_creative = {
        'id': original_creative['id'],
        'type': 'Image',
        'name': 'Awsome image',
        'api_data': imagefile
    }

    client.put(original_creative['resource_uri'],
               data=json.dumps(edited_creative),
               content_type='application/json')

    # make sure we still have two creatives
    _, response = get_resource(client, url)
    assert len(response['objects']) == 2

    # get changed creative data
    _, response = get_resource(client, original_creative['resource_uri'])

    assert response['id'] == db_object.id
    # should be different than original one
    assert not response['name'] == db_object.name
    assert not response['api_data'] == db_object.image
    # this is what it should match to
    assert response['name'] == edited_creative['name']
    assert response['api_data'].replace(settings.MEDIA_URL, '') == \
           edited_creative['api_data']
Beispiel #10
0
def test_location_autoheal(search_engine, targetvalues_all_states, client):
    raw_name = 'WC'

    raw_weird_country, _ = TargetValue.objects.get_or_create_representant(
        category=dimensions.g_location, value=[raw_name], exchange='appnexus')

    call_command('rebuild_index', interactive=False)

    assert raw_weird_country.pk in [
        int(res.pk)
        for res in SearchQuerySet().filter(django_ct='targeting.targetvalue',
                                           category=dimensions.g_location)
    ]

    response, data = get_resource(client, SEARCH_URL + '?q=' + raw_name)

    assert len(
        data['objects']) == 1, 'We should have found {0}!'.format(raw_name)

    representant, _ = TargetValue.objects.get_or_create_representant(
        category=dimensions.g_location,
        value=['Weird Country'],
        exchange='appnexus')
    raw_weird_country.representant = representant
    raw_weird_country.save()

    # WC country should be removed here
    response, data = get_resource(client, SEARCH_URL + '?q=' + raw_name)

    # out of results
    assert len(
        data['objects']) == 0, '{0} should get removed from index'.format(
            raw_name)

    # out of index
    assert raw_weird_country.pk not in [
        int(res.pk)
        for res in SearchQuerySet().filter(django_ct='targeting.targetvalue',
                                           category=dimensions.g_location)
    ]
Beispiel #11
0
def test_publisherset(client, auth_app, publisherset_db):
    client.login(username=user['username'],
                 password=user['password'])

    sets = PublisherSet.objects.filter(
        owner=auth_app.setup.models['account'][auth_test_accounts[0]['name']]
    ).all()

    _, data = get_resource(client, PUBLISHERS_SET_URL)

    assert data['meta']['total_count'] == sets.count()

    for i, pub_set in enumerate(data['objects']):

        _, pub_data = get_resource(client, pub_set['resource_uri'])

        targetvalues_count = sets[i].targetvalues.count()
        assert len(pub_data['targetvalues']) == targetvalues_count
        assert len(pub_data['targetvalues_ids']) == targetvalues_count
        for publisher in pub_data['targetvalues']:
            assert publisher['inventory'] == pub_set['inventory']
            check_data(publisher)
Beispiel #12
0
def test_not_translated_positions(kclient, publishertargetvalue_positions,
                                  search_engine):
    '''
    Attempt to run haystack search indexing with unknown positions in
    PublisherTargetValues.
    '''
    code, publishers_json = get_resource(kclient, '/api/targeting/publisher/')
    assert code == 200
    metadata = publishers_json['meta']
    assert min(metadata['total_count'], metadata['limit']) == \
           len(publishers_json['objects'])

    positions_list = [obj['positions'] for obj in publishers_json['objects']]
    empty_positions = map(lambda positions: positions == [], positions_list)
    assert all(empty_positions)
Beispiel #13
0
def test_publishers_list(client):
    publishers = PublisherTargetValue.objects.representants()

    response, data = get_resource(client, PUBLISHERS_LIST_URL)

    # publishers contains networks itself
    assert data['meta']['total_count'] < len(publishers)

    count_publishers = 0
    for publisher in publishers:
        if publisher.key == dimensions.publisher_name:
            count_publishers += 1

    assert data['meta']['total_count'] == count_publishers

    # now lets check if required data is served by API
    for publisher in data['objects']:
        check_data(publisher)
Beispiel #14
0
def test_networks_list_by_type(client, inventory_type):
    publishers = PublisherTargetValue.objects.representants()
    filtered_networks = []
    # lets filter those with given type only:
    for network in publishers:
        if network.inventory_key == inventory_type and \
                        network.key == dimensions.network:
            filtered_networks.append(network)

    inventory_filtered_url = '{0}?inventory={1}'.format(
        LIST_URL, inventory_type)

    response, data = get_resource(client, inventory_filtered_url)

    assert data['meta']['total_count'] == len(filtered_networks)

    for network in data['objects']:
        check_data(network)
Beispiel #15
0
def test_publishers_list_by_type(client, inventory_type):
    publishers = PublisherTargetValue.objects.representants()
    filtered_publishers = []
    # lets filter those with given type only:
    for publisher in publishers:
        if publisher.inventory_key == inventory_type and \
                        publisher.key == dimensions.publisher_name:
            filtered_publishers.append(publisher)

    inventory_filtered_url = '{0}?inventory={1}'.format(
        PUBLISHERS_LIST_URL, inventory_type
    )

    response, data = get_resource(client, inventory_filtered_url)

    assert data['meta']['total_count'] == len(filtered_publishers)

    for publisher in data['objects']:
        check_data(publisher)
Beispiel #16
0
def test_lotame_segments_api(client, lotame_segments):
    """Test if api resources for lotame return all segments for given segment category"""

    for LotameSegmentModel, resource_url in [
        (LotameDemographic, 'lotame_demographic'),
        (LotameAdvancedDemographic, 'lotame_advanced_demographic'),
        (LotameBehavioralInterest, 'lotame_behavioral_interest'),
        (LotameInfluencers, 'lotame_influencers'),
        (LotameOffline, 'lotame_offline'),
    ]:
        url = '/api/targeting/%s/' % resource_url
        status, segment_data = get_resource(client, url)

        database_segments = LotameSegmentModel.objects.values_list(
            'id', 'name')
        api_segments = map(lambda seg: (seg['id'], seg['name']),
                           segment_data['objects'])

        assert any(api_segments)
        assert sorted(api_segments) == sorted(database_segments)
Beispiel #17
0
def test_networks_filter_by_id(client):
    publishers_targetvalue = PublisherTargetValue.objects.representants()

    networks = []
    for network in publishers_targetvalue:
        if network.key == dimensions.network:
            networks.append(network)

    assert networks

    for network in networks:

        network_filter_url = '{0}?network_id={1}&inventory={2}'.format(
            LIST_URL, network.network_id, network.inventory_key)

        _, network_data = get_resource(client, network_filter_url)
        assert network_data['meta']['total_count'] == 1

        for network in network_data['objects']:
            check_data(network)
Beispiel #18
0
def test_huge_number_of_publishers(client, auth_app, huge_publisherlist_db):
    '''
    Test querying several pages with publishers, with big total number of pages.
    '''

    client.login(username=user['username'],
                 password=user['password'])

    total_count = len(huge_publisherlist_db['publishers_app'] + huge_publisherlist_db['publishers_site'])
    previous_data = {}
    limit = 20
    number_of_pages = (total_count + limit - 1) / limit  # make sure to take ceil

    # query over few pages (not all)
    for page in range(1, number_of_pages, 3):
        url = '{0}?limit={2}&page={1}'.format(PUBLISHERS_LIST_URL, str(page), limit)
        response, data = get_resource(client, url)

        assert response == 200
        assert len(data['objects']) == limit
        assert previous_data != data
        previous_data = data
Beispiel #19
0
def test_publishers_filter_by_networkname(client, network, count):
    filter_url = '{0}?network={1}'.format(PUBLISHERS_LIST_URL, network)

    _, data = get_resource(client, filter_url)

    assert data['meta']['total_count'] == count
Beispiel #20
0
def test_liveview_api(client, running_app, model_name):
    '''
    Check liveview api filtering and updating
    '''

    LIVEVIEW_URL = '/liveview/%s/' % model_name
    METRICS = [
        {'bid': 10, 'imp': 1},
        {'bid': 100, 'imp': 10},
        {'bid': 1000, 'imp': 100}
    ]
    METRICS_SUM = {'bid': 1110, 'imp': 111, 'winbid_ratio': '10.0%'}

    client.login(
        username=default_user[0]['username'],
        password=default_user[0]['password']
    )

    account = Account.objects.get(name=default_user[0]['account'])

    active_objects = LiveViewDataSource(model_name, account).active_objects

    # Active objects list should not be empty otherwise test will check nothing
    assert active_objects

    # Insert old metric for first object
    test_object_id = active_objects[0].public_id
    LiveViewCounter.objects.create(
        public_id=test_object_id,
        imp=1234,
        bid=4567,
        time=datetime.utcnow() - timedelta(seconds=LIVE_VIEW_PERIOD * 2)
    )

    # Get live view data
    status, live_data = get_resource(client, LIVEVIEW_URL)
    assert status == 200

    assert [(o.public_id, o.full_name) for o in active_objects] == \
           [(metric['public_id'], metric['name']) for metric in live_data]

    # Check if all metrics are empty. Metrics older than live view period
    # should not be displayed
    for metric in live_data:
        assert metric['imp'] == 0
        assert metric['bid'] == 0
        assert metric['winbid_ratio'] == '0.0%'

    # Insert fresh metrics for first object
    for index, metric in enumerate(METRICS, start=2):
        metric['time'] = datetime.utcnow() - timedelta(seconds=LIVE_VIEW_PERIOD / index)
        metric['public_id'] = test_object_id
        LiveViewCounter.objects.create(**metric)

    # Get live view data
    status, live_data = get_resource(client, LIVEVIEW_URL)
    assert status == 200

    # Check if metric sums were calculated correctly
    test_metric = filter(lambda m: test_object_id == m['public_id'], live_data)[0]
    assert test_metric['bid'] == METRICS_SUM['bid']
    assert test_metric['imp'] == METRICS_SUM['imp']
    assert test_metric['winbid_ratio'] == METRICS_SUM['winbid_ratio']
Beispiel #21
0
def test_networks_filter_by_name(client, name, count):
    filter_url = '{0}?network={1}'.format(LIST_URL, name)

    _, data = get_resource(client, filter_url)

    assert data['meta']['total_count'] == count