Beispiel #1
0
def test_no_show(driver, django_db_blocker):
    login(driver)

    with django_db_blocker.unblock():
        username = "******" + str(uuid1())
        u = DjangoUser.objects.create_user(username=username)
        ui = UserInformation.objects.create(user=u, show_my_profile=False)

    r = do_api_call_v2(driver=driver,
                       url=f'/user_information/{ui.id}/',
                       expect_fail=True)
    assert not r.ok

    r = do_api_call_v2(driver=driver,
                       url=f'/user_information/?user__username={username}')
    assert r['count'] == 0

    # test that can see my own hidden profile
    with django_db_blocker.unblock():
        UserInformation.objects.filter(user__username=test_username).update(
            show_my_profile=False)

    r = do_api_call_v2(
        driver=driver,
        url=f'/user_information/?user__username={test_username}')
    assert r['count'] == 1

    with django_db_blocker.unblock():
        UserInformation.objects.filter(user__username=test_username).update(
            show_my_profile=True)

    logout(driver)
    with django_db_blocker.unblock():
        u.delete()
def test_comment_uncertified(driver, django_db_blocker):
    # creating a user and leaving a comment, checking that it is not shown
    username = str(uuid1())
    domain = f"@{uuid1()}.com"

    with django_db_blocker.unblock():
        u = DjangoUser.objects.create_user(username=username, is_active=True)
        EmailDomain.objects.create(domain=domain,
                                   status=EmailDomain.STATUS_ACCEPTED)
        ui = UserInformation.objects.create(user=u)
        up = UserPreferences.objects.create(user=u)
        v = Video.objects.create(video_id=random_alphanumeric())
        VerifiableEmail.objects.create(user=ui, email=f"test{domain}")
        VideoComment.objects.create(user=up, video=v, comment="test")

    login(driver)

    res = do_api_call_v2(driver,
                         '/video_comments/?video__video_id=' + v.video_id)
    assert res['count'] == 0

    with django_db_blocker.unblock():
        VerifiableEmail.objects.filter(
            user=ui, email=f"test{domain}").update(is_verified=True)

    res = do_api_call_v2(driver,
                         '/video_comments/?video__video_id=' + v.video_id)
    assert res['count'] == 1

    logout(driver)

    with django_db_blocker.unblock():
        u.delete()
        v.delete()
def test_submit_video(driver):
    login(driver)

    print("Going to the expert interface...")
    expert_interface_btn = driver.find_element_by_id('expert_interface')
    expert_interface_btn.click()

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'video-left')))
    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'video-right')))

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))

    # print("Skipping tutorial")
    # skip_tutorial_btn = driver.find_element_by_id('start_comparing_button')
    # skip_tutorial_btn.click()

    vid1 = shortuuid.ShortUUID().random(length=10)
    vid2 = shortuuid.ShortUUID().random(length=10)

    def set_video(which, vid_id):
        selector = driver.find_element_by_id(which)
        c = selector.find_element_by_class_name('video_id_text_field')
        c = c.find_elements_by_tag_name('input')[0]
        c.clear()
        c.send_keys(vid_id)

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))
    set_video('video-left', vid1)
    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))
    set_video('video-right', vid2)
    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))

    expert_submit_btn = driver.find_element_by_id('expert_submit_btn')
    expert_submit_btn.click()

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_submitted_text_info')))

    assert do_api_call_v2(driver,
                          url=f"/videos/?video_id={vid1}")['count'] >= 1
    assert do_api_call_v2(driver,
                          url=f"/videos/?video_id={vid2}")['count'] >= 1

    logout(driver)
Beispiel #4
0
def test_privacy(driver, django_db_blocker):
    login(driver)

    # privacy test
    # creating a temp user
    with django_db_blocker.unblock():
        u = DjangoUser.objects.create_user(username="******" + str(uuid1()))
        ui = UserInformation.objects.create(user=u)

    def check_sensitive(res):
        assert 'gender' not in res
        assert 'race' not in res
        assert 'emails' not in res
        assert 'nationality' not in res
        assert 'residence' not in res
        assert 'moral_philosophy' not in res
        assert 'political_affiliation' not in res
        assert 'degree_of_political_engagement' not in res
        assert 'religion' not in res

    with django_db_blocker.unblock():
        ui.show_online_presence = True
        ui.save()

    res = do_api_call_v2(driver=driver, url=f'/user_information/{ui.id}/')
    check_sensitive(res)

    for x in [
            'google_scholar', 'website', 'linkedin', 'orcid', 'twitter',
            'youtube', 'researchgate'
    ]:
        assert x in res

    with django_db_blocker.unblock():
        ui.show_online_presence = False
        ui.save()
    res = do_api_call_v2(driver=driver, url=f'/user_information/{ui.id}/')
    check_sensitive(res)

    for x in [
            'google_scholar', 'website', 'linkedin', 'orcid', 'twitter',
            'youtube', 'researchgate'
    ]:
        assert x not in res

    with django_db_blocker.unblock():
        u.delete()

    logout(driver)
Beispiel #5
0
    def check_privacy_status(video_id1,
                             is_private,
                             check_db=True,
                             check_api=False):
        with django_db_blocker.unblock():
            Video.recompute_computed_properties(only_pending=True)

        priv_public = 'private' if is_private else 'public'
        WebDriverWait(driver, TIME_WAIT).until(
            EC.presence_of_element_located(
                (By.ID, f'id_video_{video_id1}_{priv_public}')))

        if check_db:
            with django_db_blocker.unblock():
                get_object_with_timeout(VideoRatingPrivacy,
                                        video__video_id=video_id1,
                                        user=up,
                                        is_public=not is_private)

        if check_api:
            pe = do_api_call_v2(driver, '/videos/?video_id=' +
                                video_id1)['results'][0]['public_experts']
            if is_private:
                assert len(pe) == 0
            else:
                assert len(pe) == 1, pe
                assert pe[0]['username'] == test_username
Beispiel #6
0
def test_user_ui_pref_videos(driver, django_db_blocker):
    """Test that user preferences are saved and videos are shown."""
    login(driver)

    with django_db_blocker.unblock():
        create_test_video(name="test")

    print("Going to user interface")
    ui_button = driver.find_element_by_id('user_interface')
    ui_button.click()

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'search_phrase')))

    print("Typing search phrase")
    search_phrase_field = driver.find_element_by_id('search_phrase')
    search_phrase_field.clear()
    search_phrase_field.send_keys('test')

    # random preferences
    np.random.seed(42)
    values = np.random.rand(len(VIDEO_FIELDS)) * 100

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_search_not_loading')))

    for f, v in zip(VIDEO_FIELDS, values):
        set_slider_value(driver, s_id='preference_slider_' + f, value=v)

        WebDriverWait(driver, TIME_WAIT).until(
            EC.presence_of_element_located((By.ID, 'id_search_not_loading')))

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_search_not_loading')))

    print("Loading recommendations")
    load_rec_btn = driver.find_element_by_id("load_recommendations")
    load_rec_btn.click()

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_search_not_loading')))

    entry = do_api_call_v2(driver, url='/user_preferences/my/')
    values_got = [entry[x] for x in VIDEO_FIELDS]
    values_transformed = values / 2 + 50
    diff = np.max(np.abs(values_transformed - values_got))
    assert diff < 5, (values_transformed, values_got)
    print("Preferences normal", diff)

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.CLASS_NAME, 'video_search_result')))

    videos = driver.find_elements_by_class_name('video_search_result')
    assert videos, "No videos returned in search, or it took too long."
    print("Got", len(videos), "videos")
    logout(driver)
def test_api_call(driver, django_db_blocker):
    with django_db_blocker.unblock():
        create_user_preferences()
    token = get_token(test_username, test_password)
    result = do_api_call_v2(driver,
                            '/user_preferences/my/',
                            headers={'Authorization': f"Token {token}"},
                            cookie_auth=False)
    assert 'id' in result
    print(result)
Beispiel #8
0
def test_rate_videos(driver, django_db_blocker):
    """Test that we can rate videos."""

    with django_db_blocker.unblock():
        ExpertRating.objects.filter(
            user__user__username=test_username).delete()

    # fixing the seed for consistent performance
    np.random.seed(41)

    login(driver)

    cleanup_rate_later(django_db_blocker)
    fill_rate_later(django_db_blocker)

    set_all_features_enabled(django_db_blocker)

    print("Going to the expert interface...")
    expert_interface_btn = driver.find_element_by_id('expert_interface')
    expert_interface_btn.click()

    # print("Skipping tutorial")
    # skip_tutorial_btn = driver.find_element_by_id('start_comparing_button')
    # skip_tutorial_btn.click()

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_expert_rating_page')))

    def process_video_selector(vid):
        """Load new video."""

        print("Processing selector", vid)

        # refreshing videos
        selector = driver.find_element_by_id(vid)

        print("Requesting new video...")
        selector.find_element_by_class_name('new_video_button').click()

    v1_id, v2_id = None, None

    # 10 attempts should be enough
    for i in range(10):
        print("Video request attempt", i)
        process_video_selector('video-left')

        WebDriverWait(driver, TIME_WAIT).until(
            EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))

        process_video_selector('video-right')

        WebDriverWait(driver, TIME_WAIT).until(
            EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))

        url_v1_v2 = driver.current_url
        assert url_v1_v2.startswith(web_url)
        url_v1_v2_split = url_v1_v2[len(web_url):].split('/')
        assert len(url_v1_v2_split) == 4
        assert url_v1_v2_split[0] == ''
        assert url_v1_v2_split[1] == 'rate'
        v1_id, v2_id = url_v1_v2_split[2:]
        if v1_id != v2_id:
            break

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))

    assert v1_id != v2_id, "Video IDs are the same after 10 attempts {v1_id} {v2_id}"
    print("Got videos", v1_id, v2_id)

    np.random.seed(45)
    values = np.random.rand(len(VIDEO_FIELDS)) * 100
    print("Will send values", values)

    for k, v in zip(VIDEO_FIELDS, values):
        set_slider_value(driver, s_id='slider_expert_' + k, value=0)
        set_slider_value(driver, s_id='slider_expert_' + k, value=v)

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_no_pending_expert')))

    print("Submitting the rating...")
    expert_submit_btn = driver.find_element_by_id('expert_submit_btn')
    expert_submit_btn.click()

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_submitted_text_info')))

    print("Checking the rating in the database...")
    registered_ratings = do_api_call_v2(
        driver, url=f"/expert_ratings/?username={test_username}")['results']

    def rating_is_match(r):
        """Is a given rating dict a match to the created one?"""
        if r['username'] != test_username:
            return False
        if r['video_1'] != v1_id:
            return False
        if r['video_2'] != v2_id:
            return False
        for i, f in enumerate(VIDEO_FIELDS):
            if np.abs(r[f] - values[i]) > 1:
                return False
        return True

    assert any([rating_is_match(r) for r in registered_ratings]), \
        f"No matching ratings found in the database, creation failed {v1_id} " \
        f"{v2_id} {values} {registered_ratings}"

    # editing the rating
    np.random.seed(46)
    values = np.random.rand(len(VIDEO_FIELDS)) * 100
    print("Will send edited values", values)

    print("Editing rating...")
    expert_submit_btn = driver.find_element_by_id('expert_submit_btn')
    expert_submit_btn.click()

    for k, v in zip(VIDEO_FIELDS, values):
        set_slider_value(driver, s_id='slider_expert_' + k, value=0)
        set_slider_value(driver, s_id='slider_expert_' + k, value=v)

    print("Submitting the edited rating...")
    expert_submit_btn = driver.find_element_by_id('expert_submit_btn')
    expert_submit_btn.click()

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_submitted_text_info')))

    print("Checking the new rating in the database...")
    registered_ratings = do_api_call_v2(driver,
                                        url=f"/expert_ratings/?"
                                        f"username={test_username}")['results']

    assert any([rating_is_match(r) for r in registered_ratings]), \
        f"No matching ratings found in the database, EDITING failed {v1_id} {v2_id} {values} " \
        f"{registered_ratings}"

    with django_db_blocker.unblock():
        assert ExpertRatingSliderChanges.objects.filter(
            context='RATE').count() > 0

    logout(driver)

    cleanup_rate_later(django_db_blocker)
Beispiel #9
0
def test_already_rated_videos(driver, django_db_blocker):
    login(driver)

    cleanup_rate_later(django_db_blocker)
    fill_rate_later(django_db_blocker)

    set_all_features_enabled(django_db_blocker)

    print("Going to the expert interface...")
    expert_interface_btn = driver.find_element_by_id('expert_interface')
    expert_interface_btn.click()

    WebDriverWait(driver, TIME_WAIT).until(
        EC.presence_of_element_located((By.ID, 'id_expert_rating_page')))

    # print("Skipping tutorial")
    # skip_tutorial_btn = driver.find_element_by_id('start_comparing_button')
    # skip_tutorial_btn.click()

    def process_video_selector(vid):
        """Load new video."""

        print("Processing selector", vid)

        # refreshing videos
        selector = driver.find_element_by_id(vid)

        print("Requesting new video...")
        selector.find_element_by_class_name('new_video_button').click()

    with django_db_blocker.unblock():
        assert ExpertRating.objects.filter(
            user__user__username=test_username).count() == 0

    for which in ['video-left', 'video-right']:
        for _ in range(5):
            process_video_selector(which)

            WebDriverWait(driver, TIME_WAIT).until(
                EC.presence_of_element_located(
                    (By.ID, 'id_no_pending_expert')))

            selector = driver.find_element_by_id(which)
            c = selector.find_element_by_class_name('video_id_text_field')
            c = c.find_elements_by_tag_name('input')[0]
            txt = c.get_property('value')
            assert txt

            assert do_api_call_v2(driver, '/expert_ratings/?video=' +
                                  txt)['count'] == 0

    # creating some ratings
    for _ in range(10):
        do_api_call_v2(driver,
                       '/expert_ratings/',
                       method=post,
                       json={
                           'video_1': shortuuid.ShortUUID().random(length=10),
                           'video_2': shortuuid.ShortUUID().random(length=10),
                           **{k: 50
                              for k in VIDEO_FIELDS}
                       })

    for which in ['video-left', 'video-right']:
        for _ in range(5):
            process_video_selector(which)

            WebDriverWait(driver, TIME_WAIT).until(
                EC.presence_of_element_located(
                    (By.ID, 'id_no_pending_expert')))

            selector = driver.find_element_by_id(which)
            c = selector.find_element_by_class_name('video_id_text_field')
            c = c.find_elements_by_tag_name('input')[0]
            txt = c.get_property('value')
            assert txt

            assert do_api_call_v2(driver,
                                  '/expert_ratings/?video=' + txt)['count']

    logout(driver)

    cleanup_rate_later(django_db_blocker)
Beispiel #10
0
def test_representative_privacy(driver, django_db_blocker):
    with django_db_blocker.unblock():
        u = DjangoUser.objects.create(username=random_alphanumeric(),
                                      is_active=True)
        UserInformation.objects.create(user=u, show_my_profile=False)

        u1 = DjangoUser.objects.create(username=random_alphanumeric(),
                                       is_active=True)
        UserInformation.objects.create(user=u1, show_my_profile=True)
        up1 = UserPreferences.objects.create(user=u1)

        v = Video.objects.create(video_id=random_alphanumeric(),
                                 name="test",
                                 **{f: 10
                                    for f in VIDEO_FIELDS})
        VideoRating.objects.create(user=up1,
                                   video=v,
                                   **{f: 10
                                      for f in VIDEO_FIELDS})

        u2 = DjangoUser.objects.create(username=random_alphanumeric(),
                                       is_active=True)
        UserInformation.objects.create(user=u2, show_my_profile=False)
        up2 = UserPreferences.objects.create(user=u2)
        VideoRating.objects.create(user=up2,
                                   video=v,
                                   **{f: 10
                                      for f in VIDEO_FIELDS})
        VideoRatingPrivacy.objects.create(video=v, user=up2, is_public=True)

        u3 = DjangoUser.objects.create(username=random_alphanumeric(),
                                       is_active=True)
        UserInformation.objects.create(user=u3, show_my_profile=False)
        up3 = UserPreferences.objects.create(user=u3)
        VideoRating.objects.create(user=up3,
                                   video=v,
                                   **{f: 10
                                      for f in VIDEO_FIELDS})
        VideoRatingPrivacy.objects.create(video=v, user=up3, is_public=False)

    login(driver)

    results = do_api_call_v2(driver, '/user_information/public_models/')
    results = [x['username'] for x in results['results']]
    assert test_username in results

    # no videos
    assert u.username not in results

    # default value
    if VideoRatingPrivacy.DEFAULT_VALUE_IS_PUBLIC:
        assert u1.username in results
    else:
        assert u1.username not in results

    # public (explicitly)
    assert u2.username in results

    # private (explicitly)
    assert u3.username not in results

    # no videos for myself, but allowed to search with own username anyway
    assert do_api_call_v2(driver,
                          '/videos/search_tournesol/?search_model=' +
                          test_username,
                          expect_fail=True).ok

    # u1 is either private or public (default value)
    if VideoRatingPrivacy.DEFAULT_VALUE_IS_PUBLIC:
        r1 = do_api_call_v2(
            driver, '/videos/search_tournesol/?reliability=1&search_model=' +
            u1.username)
        assert len(r1['results']) == 1
    else:
        assert do_api_call_v2(
            driver,
            '/videos/search_tournesol/?reliability=1&search_model=' +
            u1.username,
            expect_fail=True).status_code == 403

    # u2 has public videos
    r1 = do_api_call_v2(
        driver,
        '/videos/search_tournesol/?reliability=1&search_model=' + u2.username)
    assert len(r1['results']) == 1

    # u/u3 doesn't have public videos
    assert do_api_call_v2(driver,
                          '/videos/search_tournesol/?search_model=' +
                          u.username,
                          expect_fail=True).status_code == 403
    assert do_api_call_v2(driver,
                          '/videos/search_tournesol/?search_model=' +
                          u3.username,
                          expect_fail=True).status_code == 403

    if VideoRatingPrivacy.DEFAULT_VALUE_IS_PUBLIC:
        with django_db_blocker.unblock():
            VideoRatingPrivacy.objects.create(video=v,
                                              user=up1,
                                              is_public=False)

        assert do_api_call_v2(
            driver,
            '/videos/search_tournesol/?reliability=1&search_model=' +
            u1.username,
            expect_fail=True).status_code == 403

        results = do_api_call_v2(driver, '/user_information/public_models/')
        assert u1.username not in results
    else:
        with django_db_blocker.unblock():
            VideoRatingPrivacy.objects.create(video=v,
                                              user=up1,
                                              is_public=True)

        r1 = do_api_call_v2(
            driver, '/videos/search_tournesol/?reliability=1&search_model=' +
            u1.username)
        assert len(r1['results']) == 1

        results = do_api_call_v2(driver, '/user_information/public_models/')
        assert u1.username in results

    logout(driver)

    with django_db_blocker.unblock():
        u.delete()