def test_lookup_token_unregistered(self, mock_lookup_user): # Lookup token for a user with no registered email # Basket raises unknown user exception, then lookup-token returns None user = User(email="*****@*****.**") profile = UserProfile(user=user) mock_lookup_user.side_effect = basket.BasketException(code=basket.errors.BASKET_UNKNOWN_EMAIL) result = profile.lookup_basket_token() ok_(result is None)
def test_lookup_token_registered(self, mock_lookup_user): # Lookup token for a user with registered email # basket returns response with data, lookup_basket_token returns the token user = User(email="*****@*****.**") profile = UserProfile(user=user) mock_lookup_user.return_value = {"status": "ok", "token": "FAKETOKEN"} result = profile.lookup_basket_token() eq_("FAKETOKEN", result)
def test_lookup_token_registered(self, mock_lookup_user): # Lookup token for a user with registered email # basket returns response with data, lookup_basket_token returns the token user = User(email='*****@*****.**') profile = UserProfile(user=user) mock_lookup_user.return_value = {'status': 'ok', 'token': 'FAKETOKEN'} result = profile.lookup_basket_token() eq_('FAKETOKEN', result)
def test_lookup_token_exceptions(self, mock_lookup_user): # If basket raises any exception other than BASKET_UNKNOWN_EMAIL when # we call lookup_basket_token, lookup_basket_token passes it up the chain class SomeException(Exception): pass user = User(email='*****@*****.**') profile = UserProfile(user=user) mock_lookup_user.side_effect = SomeException with self.assertRaises(SomeException): profile.lookup_basket_token()
def test_set_privacy_level_without_save(self): user = UserFactory.create() user.userprofile.set_privacy_level(9, save=False) for field in UserProfile.privacy_fields(): eq_(getattr(user.userprofile, "privacy_{0}".format(field)), 9, "Field {0} not set".format(field)) user = User.objects.get(id=user.id) for field in UserProfile.privacy_fields(): # Compare to default privacy setting for each field. f = UserProfile._meta.get_field_by_name("privacy_{0}".format(field))[0] eq_(getattr(user.userprofile, "privacy_{0}".format(field)), f.default, "Field {0} not set".format(field))
def test_caching(self): # It would be better if this test didn't need to know how the # caching worked. # To compute the privacy fields, the code has to get all the # field names. Use mock so we can tell if that gets called. with patch.object(UserProfile._meta, 'get_all_field_names') as mock_get_all_field_names: UserProfile.privacy_fields() ok_(mock_get_all_field_names.called) # If we call privacy_fields() again, it shouldn't need to compute it all again with patch.object(UserProfile._meta, 'get_all_field_names') as mock_get_all_field_names: UserProfile.privacy_fields() ok_(not mock_get_all_field_names.called)
def test_removal_from_public_index(self): """Test that a user gets removed from public index if makes profile mozillians only again. """ before = (S(UserProfile) .indexes(UserProfile.get_index(public_index=True)) .count()) profile = self.mozillian2.userprofile profile.privacy_full_name = MOZILLIANS profile.save() sleep(1) after = (S(UserProfile) .indexes(UserProfile.get_index(public_index=True)) .count()) eq_(after+1, before)
def test_extract_document(self): user = UserFactory.create(userprofile={'allows_community_sites': False, 'allows_mozilla_sites': False, 'full_name': 'Nikos Koukos', 'bio': 'This is my bio'}) profile = user.userprofile group_1 = GroupFactory.create() group_2 = GroupFactory.create() skill_1 = SkillFactory.create() skill_2 = SkillFactory.create() LanguageFactory.create(code='fr', userprofile=profile) LanguageFactory.create(code='en', userprofile=profile) group_1.add_member(profile) group_2.add_member(profile) profile.skills.add(skill_1) profile.skills.add(skill_2) result = UserProfile.extract_document(profile.id) ok_(isinstance(result, dict)) eq_(result['id'], profile.id) eq_(result['is_vouched'], profile.is_vouched) eq_(result['region'], 'Attika') eq_(result['city'], 'Athens') eq_(result['allows_community_sites'], profile.allows_community_sites) eq_(result['allows_mozilla_sites'], profile.allows_mozilla_sites) eq_(set(result['country']), set(['gr', 'Greece'])) eq_(result['fullname'], profile.full_name.lower()) eq_(result['name'], profile.full_name.lower()) eq_(result['bio'], profile.bio) eq_(result['has_photo'], False) eq_(result['groups'], [group_1.name, group_2.name]) eq_(result['skills'], [skill_1.name, skill_2.name]) eq_(set(result['languages']), set([u'en', u'fr', u'english', u'french', u'français']))
def test_profile_model(self): fields = UserProfile.privacy_fields() eq_('', fields['ircname']) eq_('', fields['email']) ok_('is_vouched' not in fields) ok_('date_vouched' not in fields) ok_(fields['tshirt'] is None)
def test_set_privacy_level_with_save(self): user = UserFactory.create() user.userprofile.set_privacy_level(9) user = User.objects.get(id=user.id) for field in UserProfile.privacy_fields(): eq_(getattr(user.userprofile, 'privacy_{0}'.format(field)), 9, 'Field {0} not set'.format(field))
def test_profile_model(self): fields = UserProfile.privacy_fields() eq_("", fields["ircname"]) eq_("", fields["email"]) ok_("is_vouched" not in fields) ok_("date_vouched" not in fields) ok_(fields["tshirt"] is None)
def test_search_no_public_with_unvouched(self, PrivacyAwareSMock): result = UserProfile.search("foo", include_non_vouched=True) ok_(isinstance(result, Mock)) PrivacyAwareSMock.assert_any_call(UserProfile) PrivacyAwareSMock().indexes.assert_any_call("index") ok_(call().indexes().boost().query().order_by().filter(is_vouched=True) not in PrivacyAwareSMock.mock_calls) ok_(call().privacy_level(PUBLIC) not in PrivacyAwareSMock.mock_calls)
def test_search_no_public_only_vouched(self, PrivacyAwareSMock): result = UserProfile.search('foo') ok_(isinstance(result, Mock)) PrivacyAwareSMock.assert_any_call(UserProfile) PrivacyAwareSMock().indexes.assert_any_call('index') (PrivacyAwareSMock().indexes().boost() .query().order_by().filter.assert_any_call(is_vouched=True)) ok_(call().privacy_level(PUBLIC) not in PrivacyAwareSMock.mock_calls)
def test_is_public(self): for field in UserProfile.privacy_fields(): user = UserFactory.create( userprofile={"privacy_{0}".format(field): PUBLIC}) ok_( user.userprofile.is_public, "Field {0} did not set profile to public".format(field), )
def test_set_privacy_level_without_save(self): user = UserFactory.create() user.userprofile.set_privacy_level(9, save=False) for field in UserProfile.privacy_fields(): eq_( getattr(user.userprofile, "privacy_{0}".format(field)), 9, "Field {0} not set".format(field), ) user = User.objects.get(id=user.id) for field in UserProfile.privacy_fields(): # Compare to default privacy setting for each field. f = UserProfile._meta.get_field("privacy_{0}".format(field)) eq_( getattr(user.userprofile, "privacy_{0}".format(field)), f.default, "Field {0} not set".format(field), )
def test_search_public_with_unvouched(self, PrivacyAwareSMock): result = UserProfile.search( 'foo', public=True, include_non_vouched=True) ok_(isinstance(result, Mock)) PrivacyAwareSMock.assert_any_call(UserProfile) PrivacyAwareSMock().privacy_level.assert_any_call(PUBLIC) (PrivacyAwareSMock().privacy_level() .indexes.assert_any_call('public_index')) ok_(call().privacy_level().indexes().boost() .query().order_by().filter(is_vouched=True) not in PrivacyAwareSMock.mock_calls)
def search(request): num_pages = 0 limit = None people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None curated_groups = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] include_non_vouched = form.cleaned_data['include_non_vouched'] page = request.GET.get('page', 1) curated_groups = Group.get_curated() public = not (request.user.is_authenticated() and request.user.userprofile.is_vouched) profiles = UserProfile.search(query, public=public, include_non_vouched=include_non_vouched) if not public: groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if profiles.count() == 1 and not groups: return redirect('phonebook:profile_view', people[0].user.username) if paginator.count > forms.PAGINATION_LIMIT: show_pagination = True num_pages = len(people.paginator.page_range) d = dict(people=people, form=form, limit=limit, show_pagination=show_pagination, num_pages=num_pages, groups=groups, curated_groups=curated_groups) if request.is_ajax(): return render(request, 'search_ajax.html', d) return render(request, 'phonebook/search.html', d)
def search(request): num_pages = 0 limit = None people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None curated_groups = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] include_non_vouched = form.cleaned_data['include_non_vouched'] page = request.GET.get('page', 1) curated_groups = Group.get_curated() public = not (request.user.is_authenticated() and request.user.userprofile.is_vouched) profiles = UserProfile.search(query, public=public, include_non_vouched=include_non_vouched) if not public: groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if profiles.count() == 1 and not groups: return redirect('phonebook:profile_view', people[0].user.username) if paginator.count > forms.PAGINATION_LIMIT: show_pagination = True num_pages = len(people.paginator.page_range) d = dict(people=people, search_form=form, limit=limit, show_pagination=show_pagination, num_pages=num_pages, groups=groups, curated_groups=curated_groups) if request.is_ajax(): return render(request, 'search_ajax.html', d) return render(request, 'phonebook/search.html', d)
def betasearch(request): """This view is for researching new search and data filtering options. It will eventually replace the 'search' view. This view is behind the 'betasearch' waffle flag. """ limit = None people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None functional_areas = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] include_non_vouched = form.cleaned_data['include_non_vouched'] page = request.GET.get('page', 1) functional_areas = Group.get_functional_areas() public = not (request.user.is_authenticated() and request.user.userprofile.is_vouched) profiles = UserProfile.search(query, public=public, include_non_vouched=include_non_vouched) if not public: groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if profiles.count() == 1 and not groups: return redirect('phonebook:profile_view', people[0].user.username) show_pagination = paginator.count > settings.ITEMS_PER_PAGE d = dict(people=people, search_form=form, limit=limit, show_pagination=show_pagination, groups=groups, functional_areas=functional_areas) return render(request, 'phonebook/betasearch.html', d)
def betasearch(request): """This view is for researching new search and data filtering options. It will eventually replace the 'search' view. Filtering using SearchFilter does not respect privacy levels because it directly hits the db. This should be further investigated before the feature is released to the public. Meanwhile we limit searches only to vouched users. This view is behind the 'betasearch' waffle flag. """ limit = None people = [] show_pagination = False form = forms.SearchForm(request.GET) filtr = forms.SearchFilter(request.GET) if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] page = request.GET.get('page', 1) public = not (request.user.is_authenticated() and request.user.userprofile.is_vouched) profiles_matching_filter = list(filtr.qs.values_list('id', flat=True)) profiles = UserProfile.search(query, include_non_vouched=True, public=public) profiles = profiles.filter(id__in=profiles_matching_filter) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) show_pagination = paginator.count > settings.ITEMS_PER_PAGE data = dict(people=people, search_form=form, filtr=filtr, limit=limit, show_pagination=show_pagination) return render(request, 'phonebook/betasearch.html', data)
def test_search_public_only_vouched(self, PrivacyAwareSMock): result = UserProfile.search("foo", public=True) ok_(isinstance(result, Mock)) PrivacyAwareSMock.assert_any_call(UserProfile) PrivacyAwareSMock().privacy_level.assert_any_call(PUBLIC) (PrivacyAwareSMock().privacy_level().indexes.assert_any_call("public_index")) ( PrivacyAwareSMock() .privacy_level() .indexes() .boost() .query() .order_by() .filter.assert_any_call(is_vouched=True) )
def search(request): limit = None people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None curated_groups = None if form.is_valid(): query = form.cleaned_data.get("q", u"") limit = form.cleaned_data["limit"] include_non_vouched = form.cleaned_data["include_non_vouched"] page = request.GET.get("page", 1) curated_groups = Group.get_curated() public = not (request.user.is_authenticated() and request.user.userprofile.is_vouched) profiles = UserProfile.search(query, public=public, include_non_vouched=include_non_vouched) if not public: groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if profiles.count() == 1 and not groups: return redirect("phonebook:profile_view", people[0].user.username) show_pagination = paginator.count > settings.ITEMS_PER_PAGE d = dict( people=people, search_form=form, limit=limit, show_pagination=show_pagination, groups=groups, curated_groups=curated_groups, ) if request.is_ajax(): return render(request, "search_ajax.html", d) return render(request, "phonebook/search.html", d)
def search(request): limit = None people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None functional_areas = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] include_non_vouched = form.cleaned_data['include_non_vouched'] page = request.GET.get('page', 1) functional_areas = Group.get_functional_areas() public = not (request.user.is_authenticated() and request.user.userprofile.is_vouched) profiles = UserProfile.search(query, public=public, include_non_vouched=include_non_vouched) if not public: groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if profiles.count() == 1 and not groups: return redirect('phonebook:profile_view', people[0].user.username) show_pagination = paginator.count > settings.ITEMS_PER_PAGE d = dict(people=people, search_form=form, limit=limit, show_pagination=show_pagination, groups=groups, functional_areas=functional_areas) if request.is_ajax(): return render(request, 'search_ajax.html', d) return render(request, 'phonebook/search.html', d)
def test_extract_document(self): country = CountryFactory.create(name='Greece', code='gr') region = RegionFactory.create(name='attika', country=country) city = CityFactory.create(name='athens', region=region, country=country) user = UserFactory.create( userprofile={ 'geo_city': city, 'geo_region': region, 'allows_community_sites': False, 'allows_mozilla_sites': False, 'geo_country': country, 'full_name': 'Nikos Koukos', 'bio': 'This is my bio' }) profile = user.userprofile group_1 = GroupFactory.create() group_2 = GroupFactory.create() skill_1 = SkillFactory.create() skill_2 = SkillFactory.create() LanguageFactory.create(code='fr', userprofile=profile) LanguageFactory.create(code='en', userprofile=profile) group_1.add_member(profile) group_2.add_member(profile) profile.skills.add(skill_1) profile.skills.add(skill_2) result = UserProfile.extract_document(user.userprofile.id) ok_(isinstance(result, dict)) eq_(result['id'], profile.id) eq_(result['is_vouched'], profile.is_vouched) eq_(result['region'], region.name) eq_(result['city'], city.name) eq_(result['allows_community_sites'], profile.allows_community_sites) eq_(result['allows_mozilla_sites'], profile.allows_mozilla_sites) eq_(set(result['country']), set(['gr', 'Greece'])) eq_(result['fullname'], profile.full_name.lower()) eq_(result['name'], profile.full_name.lower()) eq_(result['bio'], profile.bio) eq_(result['has_photo'], False) eq_(result['groups'], [group_1.name, group_2.name]) eq_(result['skills'], [skill_1.name, skill_2.name]) eq_(set(result['languages']), set([u'en', u'fr', u'english', u'french', u'français']))
def test_extract_document(self): group_1 = GroupFactory.create() group_2 = GroupFactory.create() skill_1 = SkillFactory.create() skill_2 = SkillFactory.create() language_1 = LanguageFactory.create() language_2 = LanguageFactory.create() user = UserFactory.create( userprofile={ 'website': 'bestplaceonthenet.com', 'city': 'athens', 'region': 'attika', 'allows_community_sites': False, 'allows_mozilla_sites': False, 'country': 'gr', 'full_name': 'Nikos Koukos', 'bio': 'This is my bio' }) profile = user.userprofile profile.groups.add(group_1) profile.groups.add(group_2) profile.skills.add(skill_1) profile.skills.add(skill_2) profile.languages.add(language_1) profile.languages.add(language_2) result = UserProfile.extract_document(user.userprofile.id) ok_(isinstance(result, dict)) eq_(result['id'], profile.id) eq_(result['is_vouched'], profile.is_vouched) eq_(result['website'], profile.website) eq_(result['region'], profile.region) eq_(result['city'], profile.city) eq_(result['allows_community_sites'], profile.allows_community_sites) eq_(result['allows_mozilla_sites'], profile.allows_mozilla_sites) eq_(result['country'], ['gr', 'greece']) eq_(result['fullname'], profile.full_name.lower()) eq_(result['name'], profile.full_name.lower()) eq_(result['bio'], profile.bio) eq_(result['has_photo'], False) eq_(result['groups'], [group_1.name, group_2.name]) eq_(result['skills'], [skill_1.name, skill_2.name]) eq_(result['languages'], [language_1.name, language_2.name])
def test_extract_document(self): country = CountryFactory.create(name="Greece", code="gr") region = RegionFactory.create(name="attika", country=country) city = CityFactory.create(name="athens", region=region, country=country) user = UserFactory.create( userprofile={ "geo_city": city, "geo_region": region, "allows_community_sites": False, "allows_mozilla_sites": False, "geo_country": country, "full_name": "Nikos Koukos", "bio": "This is my bio", } ) profile = user.userprofile group_1 = GroupFactory.create() group_2 = GroupFactory.create() skill_1 = SkillFactory.create() skill_2 = SkillFactory.create() LanguageFactory.create(code="fr", userprofile=profile) LanguageFactory.create(code="en", userprofile=profile) group_1.add_member(profile) group_2.add_member(profile) profile.skills.add(skill_1) profile.skills.add(skill_2) result = UserProfile.extract_document(user.userprofile.id) ok_(isinstance(result, dict)) eq_(result["id"], profile.id) eq_(result["is_vouched"], profile.is_vouched) eq_(result["region"], region.name) eq_(result["city"], city.name) eq_(result["allows_community_sites"], profile.allows_community_sites) eq_(result["allows_mozilla_sites"], profile.allows_mozilla_sites) eq_(result["country"], country.name) eq_(result["fullname"], profile.full_name.lower()) eq_(result["name"], profile.full_name.lower()) eq_(result["bio"], profile.bio) eq_(result["has_photo"], False) eq_(result["groups"], [group_1.name, group_2.name]) eq_(result["skills"], [skill_1.name, skill_2.name]) eq_(set(result["languages"]), set([u"en", u"fr", u"english", u"french", u"français"]))
def test_extract_document(self): group_1 = GroupFactory.create() group_2 = GroupFactory.create() skill_1 = SkillFactory.create() skill_2 = SkillFactory.create() language_1 = LanguageFactory.create() language_2 = LanguageFactory.create() user = UserFactory.create(userprofile={'website': 'bestplaceonthenet.com', 'city': 'athens', 'region': 'attika', 'allows_community_sites': False, 'allows_mozilla_sites': False, 'country': 'gr', 'full_name': 'Nikos Koukos', 'bio': 'This is my bio'}) profile = user.userprofile profile.groups.add(group_1) profile.groups.add(group_2) profile.skills.add(skill_1) profile.skills.add(skill_2) profile.languages.add(language_1) profile.languages.add(language_2) result = UserProfile.extract_document(user.userprofile.id) ok_(isinstance(result, dict)) eq_(result['id'], profile.id) eq_(result['is_vouched'], profile.is_vouched) eq_(result['website'], profile.website) eq_(result['region'], profile.region) eq_(result['city'], profile.city) eq_(result['allows_community_sites'], profile.allows_community_sites) eq_(result['allows_mozilla_sites'], profile.allows_mozilla_sites) eq_(result['country'], ['gr', 'greece']) eq_(result['fullname'], profile.full_name.lower()) eq_(result['name'], profile.full_name.lower()) eq_(result['bio'], profile.bio) eq_(result['has_photo'], False) eq_(result['groups'], [group_1.name, group_2.name]) eq_(result['skills'], [skill_1.name, skill_2.name]) eq_(result['languages'], [language_1.name, language_2.name])
def index_all_profiles(): # Get an es object, delete index and re-create it es = get_es(timeout=settings.ES_INDEXING_TIMEOUT) mappings = {"mappings": {UserProfile._meta.db_table: UserProfile.get_mapping()}} def _recreate_index(index): try: es.delete_index_if_exists(index) except pyes.exceptions.IndexMissingException: pass es.create_index(index, settings=mappings) _recreate_index(settings.ES_INDEXES["default"]) _recreate_index(settings.ES_INDEXES["public"]) # mozillians index ids = UserProfile.objects.complete().values_list("id", flat=True) ts = [index_objects.subtask(args=[UserProfile, chunk, False]) for chunk in chunked(sorted(list(ids)), 150)] # public index ids = UserProfile.objects.complete().public_indexable().privacy_level(PUBLIC).values_list("id", flat=True) ts += [index_objects.subtask(args=[UserProfile, chunk, True]) for chunk in chunked(sorted(list(ids)), 150)] TaskSet(ts).apply_async()
def test_get_index(self): ok_(UserProfile.get_index(public_index=False), 'bar')
def create(cls, **kwargs): """After creating User object, update ElasticSearch index.""" user = super(UserFactory, cls).create(**kwargs) UserProfile.refresh_index(public_index=False) UserProfile.refresh_index(public_index=True) return user
def setUp(self): UserProfile.clear_privacy_fields_cache()
def test_is_public(self): for field in UserProfile.privacy_fields(): user = UserFactory.create( userprofile={'privacy_{0}'.format(field): PUBLIC}) ok_(user.userprofile.is_public, 'Field {0} did not set profile to public'.format(field))
def test_email_private(self): user = UserFactory.create() public_profile = user.userprofile public_profile.set_instance_privacy_level(PUBLIC) eq_(public_profile.email, UserProfile.privacy_fields()['email'])
def test_tshirt_public(self): user = UserFactory.create(userprofile={'tshirt': 9}) public_profile = user.userprofile public_profile.set_instance_privacy_level(PUBLIC) eq_(public_profile.tshirt, UserProfile.privacy_fields()['tshirt'])
def test_get_index_public(self): ok_(UserProfile.get_index(public_index=True), 'foo')
def test_get_mapping(self): ok_(UserProfile.get_mapping())
from import_export.resources import ModelResource from sorl.thumbnail.admin import AdminImageMixin import mozillians.users.tasks from mozillians.common.helpers import get_datetime from mozillians.groups.models import GroupMembership, Skill from mozillians.users.cron import index_all_profiles from mozillians.users.models import (PUBLIC, Language, ExternalAccount, Vouch, UserProfile, UsernameBlacklist) admin.site.unregister(Group) Q_PUBLIC_PROFILES = Q() for field in UserProfile.privacy_fields(): key = 'privacy_%s' % field Q_PUBLIC_PROFILES |= Q(**{key: PUBLIC}) def subscribe_to_basket_action(): """Subscribe to Basket action.""" def subscribe_to_basket(modeladmin, request, queryset): """Subscribe to Basket or update details of already subscribed.""" ts = [(mozillians.users.tasks.update_basket_task .subtask(args=[userprofile.id])) for userprofile in queryset] TaskSet(ts).apply_async() messages.success(request, 'Basket update started.') subscribe_to_basket.short_description = 'Subscribe to or Update Basket'