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_representative_search(driver, django_db_blocker): with django_db_blocker.unblock(): u = DjangoUser.objects.create(username=random_alphanumeric(), is_active=True) up = UserPreferences.objects.create(user=u) UserInformation.objects.create(user=u, show_my_profile=True) video_id = create_test_video() video = Video.objects.get(video_id=video_id) ratings = {f: np.random.randn() for f in VIDEO_FIELDS} VideoRating.objects.create(user=up, video=video, **ratings) VideoRatingPrivacy.objects.create(user=up, video=video, is_public=True) login(driver) ui_button = driver.find_element_by_id('user_interface') ui_button.click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, 'search_options'))) driver.find_element_by_class_name('search_options').click() inp_model = driver.find_element_by_id('autocomplete_search_model') inp_model.send_keys(len('Aggregated') * [Keys.BACK_SPACE]) inp_model.send_keys(f"{u.username}'s representative") driver.find_element_by_class_name('MuiAutocomplete-popper').click() 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'))) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located( (By.CLASS_NAME, f'video_card_id_{video_id}'))) # now will only see 1 video assert driver.find_elements_by_class_name(f'video_card_id_{video_id}') logout(driver) with django_db_blocker.unblock(): u.delete() Video.objects.filter(video_id=video_id).delete()
def test_user_profile_navigate(driver, django_db_blocker): """Test that going from another person's profile to mine works, see #309.""" with django_db_blocker.unblock(): other_username = random_alphanumeric() u = DjangoUser.objects.create_user(username=other_username) print(other_username) login(driver) with django_db_blocker.unblock(): UserInformation.objects.filter(user__username=test_username)\ .update(first_name='Selenium') UserInformation.objects.filter(user__username=other_username)\ .update(first_name='Other user') driver.get(web_url + '/user/' + other_username) def current_profile_first_name(): WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, "id_user_page_loaded"))) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located( (By.ID, "id_first_last_name_certified_user"))) result = driver.find_element_by_id( 'id_first_last_name_certified_user').text print('firstname', result) return result assert current_profile_first_name().startswith('Other user') WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, "personal_info_menu"))) driver.find_element_by_id('personal_info_menu').click() assert current_profile_first_name().startswith('Selenium') with django_db_blocker.unblock(): u.delete() logout(driver)
def test_submit_to_add_later_url(driver, django_db_blocker): """Add video to rate later list via a URL.""" login(driver) video_id = random_alphanumeric() driver.get(web_url + '/rate_later_add/' + video_id) # checking that submission succeeded WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_rate_later_submit_ok'))) # checking that list is present WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, 'class_rate_later_list'))) # checking that the video is in the list WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, f'id_{video_id}_remove_rate_later'))) # doing the same thing, but now will get a warning driver.refresh() # checking that submission succeeded WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_rate_later_submit_already_exists'))) # checking that list is present WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, 'class_rate_later_list'))) # checking that the video is in the list WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, f'id_{video_id}_remove_rate_later'))) with django_db_blocker.unblock(): Video.objects.filter(video_id=video_id).delete() logout(driver)
def test_signup_verify_email(driver, django_db_blocker): # removing old emails shutil.rmtree(EMAIL_FILE_PATH) os.makedirs(EMAIL_FILE_PATH, exist_ok=True) with django_db_blocker.unblock(): pending_domain = f"@{random_alphanumeric()}.com" accepted_domain = f"@{random_alphanumeric()}.com" rejected_domain = f"@{random_alphanumeric()}.com" # EmailDomain.objects.create(domain=pending_domain, # status=EmailDomain.STATUS_PENDING) EmailDomain.objects.create(domain=accepted_domain, status=EmailDomain.STATUS_ACCEPTED) EmailDomain.objects.create(domain=rejected_domain, status=EmailDomain.STATUS_REJECTED) signup(driver, django_db_blocker, username=random_alphanumeric(), password=secrets.token_urlsafe(32), email=f"test_first{pending_domain}") WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, "signup_button"))) two_last = [get_last_email(offset) for offset in [-1, -2]] two_last_from = [x.get('From', "") for x in two_last] assert any([x == EMAIL_NEWDOMAIN_ADDRESS for x in two_last_from]), two_last_from domains = { 'pending': f"{random_alphanumeric()}{pending_domain}", 'rejected': f"{random_alphanumeric()}{rejected_domain}", 'accepted': f"{random_alphanumeric()}{accepted_domain}", } for email_type, email_address in domains.items(): driver.get(web_url) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, "signup_button"))) # sign up driver.find_element_by_id('signup_button').click() password = secrets.token_urlsafe(32) user_data = { 'root_username': str(uuid1()), 'root_email': email_address, 'root_password': password, 'root_password2': password } for key, val in user_data.items(): elem = driver.find_element_by_id(key) elem.clear() elem.send_keys(val) # accepting the privacy policy pp_ckbox = driver.find_element_by_id('root_shrivacy_policy') if not pp_ckbox.get_property('checked'): pp_ckbox.click() buttons = driver.find_elements_by_tag_name('button') buttons = [x for x in buttons if x.get_attribute('type') == 'submit'] assert len(buttons) == 1 buttons[0].click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located( (By.ID, "button_home_page_to_verify_id"))) # going to the home page driver.find_element_by_id('button_home_page_to_verify_id').click() email_parsed = get_last_email() email_payload = None for payload in email_parsed.walk(): if payload.get_content_type() == 'text/html': email_payload = payload.get_payload() assert email_payload html_parsed = html.parse(StringIO(email_payload)) assert html_parsed.xpath("//p[@id = 'confirmation_text_id']") for email_other_type in domains.keys(): items = html_parsed.xpath( f"//*[@id = 'email_{email_other_type}_id']") if email_other_type == email_type: assert items else: assert not items, (email_type, email_other_type, email_payload, email_address) # confirming e-mail address confirm_link = html_parsed.xpath( "//a[@id = 'confirmation_link_id']")[0].get('href') confirm_link = confirm_link.replace(EMAIL_PAGE_DOMAIN, 'http://127.0.0.1:8000/') print("Navigating to", confirm_link) driver.get(confirm_link) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located( (By.ID, "button_home_page_verified_id"))) # going to the home page driver.find_element_by_id('button_home_page_verified_id').click() open_tournesol(driver) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, "login_button"))) login(driver, test_username=user_data['root_username'], test_password=user_data['root_password']) logout(driver) with django_db_blocker.unblock(): DjangoUser.objects.filter( username=user_data['root_username']).delete()
def test_skipped_videos(driver, django_db_blocker): """Test that we can rate videos.""" cleanup_rate_later(django_db_blocker) # fixing the seed for consistent performance np.random.seed(41) login(driver) 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'))) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located( (By.CLASS_NAME, 'class_sample_no_video'))) with django_db_blocker.unblock(): my_prefs = UserPreferences.objects.get(user__username=test_username) ExpertRating.objects.filter(user=my_prefs).delete() VideoSelectorSkips.objects.filter(user=my_prefs).delete() # ratings videos = [ Video.objects.create(video_id=random_alphanumeric()) for _ in range(3) ] [VideoRateLater.objects.create(user=my_prefs, video=v) for v in videos] driver.refresh() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_expert_rating_page'))) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_no_pending_expert_video'))) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_no_pending_expert'))) 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_hist = [] v2_hist = [] def get_v1_v2(): 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:] return v1_id, v2_id v1_id, v2_id = get_v1_v2() v1_hist.append(v1_id) v2_hist.append(v2_id) i = 0 while i < 5 or v1_id == v2_id: print("Video request attempt", i) process_video_selector('video-left') process_video_selector('video-right') WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_no_pending_expert'))) v1_id, v2_id = get_v1_v2() v1_hist.append(v1_id) v2_hist.append(v2_id) i += 1 assert v1_id != v2_id, "Video IDs are the same after 10 attempts {v1_id} {v2_id}" print("Submitting the rating...") expert_submit_btn = driver.find_element_by_id('expert_submit_btn') expert_submit_btn.click() # now must have skipped videos with django_db_blocker.unblock(): v1_hist_filtered = list( filter(lambda x: get_object_or_None(Video, video_id=x) is not None, v1_hist))[:-1] v2_hist_filtered = list( filter(lambda x: get_object_or_None(Video, video_id=x) is not None, v2_hist))[:-1] skips = filter_object_with_timeout( VideoSelectorSkips, user=my_prefs, min_count=len(v1_hist_filtered) + len(v2_hist_filtered)) \ .order_by('datetime_add').values('video__video_id') skips = [x['video__video_id'] for x in skips] # valid videos all but last one print(skips) print(v1_hist_filtered) print(v2_hist_filtered) def array_levenstein(a, b): all_values = list(set(a).union(set(b))) assert len(all_values) < 27 value_map = { v: string.ascii_lowercase[i] for (i, v) in enumerate(all_values) } a_mapped = ''.join([value_map[t] for t in a]) b_mapped = ''.join([value_map[t] for t in b]) print(a_mapped, b_mapped) return editdistance.eval(str(a_mapped), str(b_mapped)) d1 = array_levenstein(v1_hist_filtered + v2_hist_filtered, skips) d2 = array_levenstein(v2_hist_filtered + v1_hist_filtered, skips) assert d1 <= 1 or d2 <= 1, (d1, d2) logout(driver) with django_db_blocker.unblock(): ExpertRating.objects.filter(user=my_prefs).delete() VideoSelectorSkips.objects.filter(user=my_prefs).delete() cleanup_rate_later(django_db_blocker)
def test_rate_later_top_k(driver, django_db_blocker): # creating popular videos... with django_db_blocker.unblock(): # determining current max views... max_views = 0 if Video.objects.all().count() > 0: max_views = Video.objects.all().aggregate(Max(F('views')))['views__max'] video_ids = [random_alphanumeric() for _ in range(n_top_popular)] Video.objects.bulk_create([Video(video_id=vid, views=max_views + 1) for vid in video_ids]) VideoRateLater.objects.filter(user__user__username=test_username).delete() video_ids_set = set(video_ids) login(driver) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'rate_later_menu'))) print("Going to the rate later page") expert_interface_btn = driver.find_element_by_id('rate_later_menu') expert_interface_btn.click() assert not element_present_now(driver, 'id_controls_prev_next') assert not element_present_now(driver, 'id_big_expert_interface') def add_from_topk(): # requesting new video WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, 'new_video_button'))) elems = driver.find_elements_by_class_name('new_video_button') assert len(elems) == 1 elems[0].click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_top_video_videocard'))) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_big_add_rate_later'))) driver.find_element_by_id('id_big_add_rate_later').click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_rate_later_submit_ok'))) with django_db_blocker.unblock(): ids_vrl = list(VideoRateLater.objects.filter( user__user__username=test_username).values('video__video_id')) ids_vrl = [x['video__video_id'] for x in ids_vrl] assert set(ids_vrl).issubset(video_ids_set) return len(ids_vrl) for i in range(1, minNumRateLater + 2): assert add_from_topk() == i if i >= minNumRateLater: WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_big_expert_interface'))) else: WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_recommend_add_more'))) # trying to add manually now... elem = driver.find_element_by_class_name('video_id_text_field') elem = elem.find_element_by_tag_name('input') elem.clear() elem.send_keys('abacaba') WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_big_add_rate_later'))) driver.find_element_by_id('id_big_add_rate_later').click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_rate_later_submit_ok'))) with django_db_blocker.unblock(): get_object_with_timeout(VideoRateLater, user__user__username=test_username, video__video_id='abacaba') logout(driver)
def create_toy_data(django_db_blocker, driver, n_users=10, n_videos=10, n_ratings=10): """Create a random database.""" with django_db_blocker.unblock(): users = [DjangoUser.objects.create_user( username=random_alphanumeric(), is_active=True) for u in range(n_users)] video_ids = [create_test_video() for v in range(n_videos)] # creating user preferences and user informations login(driver) logout(driver) # creating email domains status_to_domain = {EmailDomain.STATUS_ACCEPTED: "@accepted.com", EmailDomain.STATUS_REJECTED: "@rejected.com", EmailDomain.STATUS_PENDING: "@pending.com"} with django_db_blocker.unblock(): for status, domain in status_to_domain.items(): EmailDomain.objects.create(domain=domain, status=status) # obtaining user information/user preferences with django_db_blocker.unblock(): ups = [UserPreferences.objects.get(user__username=u.username) for u in users] uis = [UserInformation.objects.get(user__username=u.username) for u in users] # setting show_my_profile and show_online_presence to random values with django_db_blocker.unblock(): for ui in uis: ui.show_my_profile = np.random.rand() > 0.5 ui.show_online_presence = np.random.rand() > 0.5 # filling in user informations with django_db_blocker.unblock(): for ui in uis: # filling online presence for field in UserInformation.ONLINE_FIELDS: domain = UserInformation._domain_startswith.get(field, "mydomain.com") setattr(ui, field, f"https://{domain}/{random_alphanumeric()}") # filling personal data for field in UserInformation.PROFILE_FIELDS: setattr(ui, field, random_alphanumeric()) # filling in protected attributes protected_map = { 'birth_year': 1990, 'gender': 'Male', 'nationality': 'Swiss', 'residence': 'Switzerland', 'race': 'Latino or Hispanic', 'political_affiliation': 'Centrist', 'religion': 'Atheist', 'degree_of_political_engagement': 'Light', 'moral_philosophy': 'Utilitatian' } for key, val in protected_map.items(): setattr(ui, key, val) ui.save() # assigning random emails with django_db_blocker.unblock(): for ui in uis: domain = np.random.choice(list(status_to_domain.values())) email = f"{random_alphanumeric()}{domain}" verified = np.random.rand() > 0.8 VerifiableEmail.objects.create(email=email, user=ui, is_verified=verified) # creating random ratings with django_db_blocker.unblock(): for up in ups: for _ in range(n_ratings): fields = {} for f in VIDEO_FIELDS: fields[f] = np.random.rand() * 100 fields[f + "_weight"] = np.random.rand() + 1 vid1 = np.random.choice(video_ids) vid2 = np.random.choice(video_ids) v1 = Video.objects.get(video_id=vid1) v2 = Video.objects.get(video_id=vid2) try: ExpertRating.objects.create(user=up, video_1=v1, video_2=v2, **fields) except IntegrityError: print("Duplicate random comparison (OK)") pass # assigning random privacy settings with django_db_blocker.unblock(): for up in ups: for video_id in video_ids: if np.random.rand() > 0.5: continue public = np.random.rand() > 0.8 VideoRatingPrivacy.objects.create( video=Video.objects.get(video_id=video_id), user=up, is_public=public)
def test_thank_unthank(driver, django_db_blocker): with django_db_blocker.unblock(): video_id = create_test_video() video = Video.objects.get(video_id=video_id) video_id1 = create_test_video() video1 = Video.objects.get(video_id=video_id1) domain = EmailDomain.objects.create(status=EmailDomain.STATUS_ACCEPTED, domain="@" + random_alphanumeric() + ".com") # creating a certified user with ratings of the video other_user = DjangoUser.objects.create_user( username=random_alphanumeric(), is_active=True) oup = UserPreferences.objects.create(user=other_user) oui = UserInformation.objects.create(user=other_user) ExpertRating.objects.create(user=oup, video_1=video, video_2=video1) ve = VerifiableEmail.objects.create(user=oui, email="aba" + domain.domain, is_verified=True) login(driver) open_more_menu(driver) WebDriverWait(driver, TIME_WAIT).until( EC.visibility_of_element_located((By.ID, 'video_details_menu'))) print("Going to the details page") expert_interface_btn = driver.find_element_by_id('video_details_menu') expert_interface_btn.click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, 'video_id_text_field'))) elem = driver.find_element_by_class_name('video_id_text_field') elem = elem.find_element_by_tag_name('input') # setting the video ID elem.clear() elem.send_keys(video_id, Keys.HOME) if elem.get_attribute('value') != video_id: elem.send_keys(3 * [Keys.DELETE]) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, f'id_{video_id}_thank'))) driver.find_element_by_id(f'id_{video_id}_thank').click() with django_db_blocker.unblock(): assert get_object_with_timeout( VideoRatingThankYou, video__video_id=video_id, thanks_from__user__username=test_username, thanks_to__user__username=other_user.username) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, f'id_{video_id}_unthank'))) driver.find_element_by_id(f'id_{video_id}_unthank').click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, f'id_{video_id}_thank'))) with django_db_blocker.unblock(): assert VideoRatingThankYou.objects.filter( video__video_id=video_id, thanks_from__user__username=test_username, thanks_to__user__username=other_user.username).count() == 0 logout(driver) with django_db_blocker.unblock(): Video.objects.filter(video_id=video_id).delete() Video.objects.filter(video_id=video_id1).delete() ve.delete() other_user.delete()
def test_mention(driver, django_db_blocker): login(driver) with django_db_blocker.unblock(): video_id = create_test_video() domain = EmailDomain.objects.create(status=EmailDomain.STATUS_ACCEPTED, domain="@" + random_alphanumeric() + ".com") ve = VerifiableEmail.objects.create( user=UserInformation.objects.get(user__username=test_username), email="aba" + domain.domain, is_verified=True) open_more_menu(driver) WebDriverWait(driver, TIME_WAIT).until( EC.visibility_of_element_located((By.ID, 'video_details_menu'))) print("Going to the details page") expert_interface_btn = driver.find_element_by_id('video_details_menu') expert_interface_btn.click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, 'video_id_text_field'))) elem = driver.find_element_by_class_name('video_id_text_field') elem = elem.find_element_by_tag_name('input') # setting the video ID elem.clear() elem.send_keys(video_id, Keys.HOME) if elem.get_attribute('value') != video_id: elem.send_keys(3 * [Keys.DELETE]) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located( (By.CLASS_NAME, f'comment_editor_{video_id}_undefined'))) # sending the comment editor = driver.find_element_by_class_name( f'comment_editor_{video_id}_undefined') editor.find_element_by_class_name('public-DraftEditor-content').send_keys( '@' + test_username) # selecting the mention suggestion WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located( (By.CLASS_NAME, 'rdw-suggestion-option'))) elems = driver.find_elements_by_class_name('rdw-suggestion-option') elems = [x for x in elems if test_username in x.text] assert len(elems) == 1 WebDriverWait(driver, TIME_WAIT).until(EC.visibility_of(elems[0])) elems[0].click() action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(elems[0], elems[0].rect['width'] / 2, elems[0].rect['height'] / 2) action.click() action.perform() WebDriverWait(driver, TIME_WAIT).until(EC.invisibility_of_element(elems[0])) driver.find_elements_by_class_name( f'comment_editor_submit_{video_id}_undefined')[0].click() with django_db_blocker.unblock(): assert get_object_with_timeout(VideoComment, video__video_id=video_id) # going to mentions... driver.find_element_by_id('personal_info_menu').click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_mentions'))) driver.find_element_by_id('id_mentions').click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located( (By.CLASS_NAME, 'class_li_comment_mention'))) assert len( driver.find_elements_by_class_name('class_li_comment_mention')) == 1 logout(driver) with django_db_blocker.unblock(): Video.objects.filter(video_id=video_id).delete() ve.delete()
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()