def notify_failed(file_pks, job_pk, data, **kw): log.info("[%s@None] Notifying failed for job %s." % (len(file_pks), job_pk)) job = ValidationJob.objects.get(pk=job_pk) set_user(get_task_user()) for result in ValidationResult.objects.filter(validation_job=job, file__pk__in=file_pks): file = result.file version = file.version addon = version.addon context = get_context(addon, version, job, [result], fileob=file) for author in addon.authors.all(): log.info( u"Emailing %s%s for addon %s, file %s about " "error from bulk validation job %s" % (author.email, " [PREVIEW]" if data["preview_only"] else "", addon.pk, file.pk, job_pk) ) args = (Template(data["subject"]).render(context), Template(data["text"]).render(context)) kwargs = dict(from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[author.email]) if data["preview_only"]: job.preview_failure_mail(*args, **kwargs) else: send_mail(*args, **kwargs) amo.log( amo.LOG.BULK_VALIDATION_EMAILED, addon, version, details={"version": version.version, "file": file.filename, "target": job.target_version.version}, )
def setup_payment_acct(self, make_owner, user=None, bango_id=123): # Set up Solitude return values. api = self.sol.api # Set up Solitude return values. api.generic.product.get_object.side_effect = ObjectDoesNotExist api.generic.product.post.return_value = {'resource_uri': 'gpuri'} api.bango.product.get_object.side_effect = ObjectDoesNotExist api.bango.product.post.return_value = { 'resource_uri': 'bpruri', 'bango_id': 123} if not user: user = self.user amo.set_user(user) if make_owner: # Make owner AddonUser.objects.create(addon=self.webapp, user=user, role=amo.AUTHOR_ROLE_OWNER) # Set up an existing bank account. seller = SolitudeSeller.objects.create( resource_uri='/path/to/sel', user=user, uuid='uuid-%s' % user.pk) acct = PaymentAccount.objects.create( user=user, uri='asdf-%s' % user.pk, name='test', inactive=False, seller_uri='suri-%s' % user.pk, solitude_seller=seller, bango_package_id=123, agreed_tos=True) return acct, api, user
def test_update_logs(self): addon = Addon.objects.get(id=3615) set_user(UserProfile.objects.all()[0]) addon.versions.all().delete() entries = ActivityLog.objects.all() eq_(entries[0].action, amo.LOG.CHANGE_STATUS.id)
def setup_payment_acct(self, make_owner, user=None, bango_id=123): # Set up Solitude return values. gen = self.generic_patcher prov = self.bango_patcher gen.product.get_object.side_effect = ObjectDoesNotExist gen.product.post.return_value = {"resource_uri": "gpuri"} prov.product.get_object.side_effect = ObjectDoesNotExist prov.product.post.return_value = {"resource_uri": "bpruri", "bango_id": 123} if not user: user = self.user amo.set_user(user) if make_owner: # Make owner AddonUser.objects.create(addon=self.webapp, user=user, role=amo.AUTHOR_ROLE_OWNER) # Set up an existing bank account. seller = SolitudeSeller.objects.create(resource_uri="/path/to/sel", user=user, uuid="uuid-%s" % user.pk) acct = PaymentAccount.objects.create( user=user, uri="asdf-%s" % user.pk, name="test", inactive=False, seller_uri="suri-%s" % user.pk, solitude_seller=seller, account_id=123, agreed_tos=True, ) return acct, user
def test_version_delete_logs(self): user = UserProfile.objects.get(pk=55021) amo.set_user(user) version = Version.objects.get(pk=81551) eq_(ActivityLog.objects.count(), 0) version.delete() eq_(ActivityLog.objects.count(), 2)
def setUp(self): self.login_as_editor() amo.set_user(UserProfile.objects.get(username='******')) review = self.make_review() for i in xrange(30): amo.log(amo.LOG.APPROVE_REVIEW, review, review.addon) amo.log(amo.LOG.DELETE_REVIEW, review.id, review.addon)
def update_maxversions(version_pks, job_pk, data, **kw): log.info("[%s@%s] Updating max version for job %s." % (len(version_pks), update_maxversions.rate_limit, job_pk)) job = ValidationJob.objects.get(pk=job_pk) set_user(get_task_user()) dry_run = data["preview_only"] app_id = job.target_version.application stats = collections.defaultdict(int) stats["processed"] = 0 stats["is_dry_run"] = int(dry_run) for version in Version.objects.filter(pk__in=version_pks): stats["processed"] += 1 addon = version.addon file_pks = version.files.values_list("pk", flat=True) errors = ValidationResult.objects.filter(validation_job=job, file__pk__in=file_pks).values_list( "errors", flat=True ) if any(errors): stats["invalid"] += 1 log.info( "Version %s for addon %s not updated, " "one of the files did not pass validation" % (version.pk, version.addon.pk) ) continue for app in version.apps.filter( application=job.curr_max_version.application, max__version_int__gte=job.curr_max_version.version_int, max__version_int__lt=job.target_version.version_int, ): stats["bumped"] += 1 log.info( "Updating version %s%s for addon %s from version %s " "to version %s" % ( version.pk, " [DRY RUN]" if dry_run else "", version.addon.pk, job.curr_max_version.version, job.target_version.version, ) ) app.max = job.target_version if not dry_run: app.save() amo.log( amo.LOG.MAX_APPVERSION_UPDATED, version.addon, version, details={"version": version.version, "target": job.target_version.version, "application": app_id}, ) log.info( "[%s@%s] bulk update stats for job %s: {%s}" % ( len(version_pks), update_maxversions.rate_limit, job_pk, ", ".join("%s: %s" % (k, stats[k]) for k in sorted(stats.keys())), ) )
def test_associate_acct_to_app(self): # Set up Solitude return values. api = self.sol.api # Set up Solitude return values. api.generic.product.get_object.side_effect = ObjectDoesNotExist api.generic.product.post.return_value = {'resource_uri': 'gpuri'} api.bango.product.get_object.side_effect = ObjectDoesNotExist api.bango.product.post.return_value = { 'resource_uri': 'bpruri', 'bango_id': 123} # Set up an existing bank account. user = UserProfile.objects.get(email=self.username) amo.set_user(user) seller = SolitudeSeller.objects.create( resource_uri='/path/to/sel', user=user) acct = PaymentAccount.objects.create( user=user, uri='asdf', name='test', inactive=False, solitude_seller=seller, bango_package_id=123, agreed_tos=True) # Associate account with app. res = self.client.post( self.url, self.get_postdata({'toggle-paid': 'paid', 'price': self.price.pk, 'accounts': acct.pk}), follow=True) self.assertNoFormErrors(res) eq_(res.status_code, 200) eq_(self.webapp.app_payment_account.payment_account.pk, acct.pk) kw = api.bango.product.post.call_args[1]['data'] ok_(kw['secret'], kw) kw = api.generic.product.post.call_args[1]['data'] eq_(kw['access'], ACCESS_PURCHASE)
def test_rejected(self): comments = "oh no you di'nt!!" amo.set_user(UserProfile.objects.get(username='******')) amo.log(amo.LOG.REJECT_VERSION, self.webapp, self.webapp.current_version, user_id=999, details={'comments': comments, 'reviewtype': 'pending'}) self.webapp.update(status=amo.STATUS_REJECTED) amo.tests.make_rated(self.webapp) (self.webapp.versions.latest() .all_files[0].update(status=amo.STATUS_DISABLED)) r = self.client.get(self.url) eq_(r.status_code, 200) doc = pq(r.content)('#version-status') eq_(doc('.status-rejected').length, 1) eq_(doc('#rejection').length, 1) eq_(doc('#rejection blockquote').text(), comments) my_reply = 'fixed just for u, brah' r = self.client.post(self.url, {'notes': my_reply, 'resubmit-app': ''}) self.assertRedirects(r, self.url, 302) webapp = self.get_webapp() eq_(webapp.status, amo.STATUS_PENDING, 'Reapplied apps should get marked as pending') eq_(webapp.versions.latest().all_files[0].status, amo.STATUS_PENDING, 'Files for reapplied apps should get marked as pending') action = amo.LOG.WEBAPP_RESUBMIT assert AppLog.objects.filter( addon=webapp, activity_log__action=action.id).exists(), ( "Didn't find `%s` action in logs." % action.short)
def test_associate_acct_to_app(self): # Set up Solitude return values. self.sol.get_product.return_value = {'meta': {'total_count': 0}} self.sol.post_product.return_value = {'resource_uri': 'gpuri'} self.sol.get_product_bango.return_value = {'meta': {'total_count': 0}} self.sol.post_product_bango.return_value = { 'resource_uri': 'bpruri', 'bango_id': 123} # Set up an existing bank account. user = UserProfile.objects.get(email=self.username) amo.set_user(user) seller = SolitudeSeller.objects.create( resource_uri='/path/to/sel', user=user) acct = PaymentAccount.objects.create( user=user, uri='asdf', name='test', inactive=False, solitude_seller=seller, bango_package_id=123, agreed_tos=True) # Associate account with app. res = self.client.post( self.url, self.get_postdata({'toggle-paid': 'paid', 'price': self.price.pk, 'accounts': acct.pk}), follow=True) self.assertNoFormErrors(res) eq_(res.status_code, 200) eq_(self.webapp.app_payment_account.payment_account.pk, acct.pk) # Make sure the product was created with some properties we care about. kw = self.sol.post_product.call_args[1]['data'] assert kw['public_id'], kw assert kw['external_id'], kw assert kw['secret'], kw
def test_rejected(self): comments = "oh no you di'nt!!" amo.set_user(UserProfile.objects.get(username="******")) amo.log( amo.LOG.REJECT_VERSION, self.webapp, self.webapp.current_version, user_id=999, details={"comments": comments, "reviewtype": "pending"}, ) self.webapp.update(status=amo.STATUS_REJECTED) (self.webapp.versions.latest().all_files[0].update(status=amo.STATUS_DISABLED)) r = self.client.get(self.url) eq_(r.status_code, 200) doc = pq(r.content)("#version-status") eq_(doc(".status-rejected").length, 1) eq_(doc("#rejection").length, 1) eq_(doc("#rejection blockquote").text(), comments) my_reply = "fixed just for u, brah" r = self.client.post(self.url, {"notes": my_reply, "resubmit-app": ""}) self.assertRedirects(r, self.url, 302) webapp = self.get_webapp() eq_(webapp.status, amo.STATUS_PENDING, "Reapplied apps should get marked as pending") eq_( webapp.versions.latest().all_files[0].status, amo.STATUS_PENDING, "Files for reapplied apps should get marked as pending", ) action = amo.LOG.WEBAPP_RESUBMIT assert AppLog.objects.filter(addon=webapp, activity_log__action=action.id).exists(), ( "Didn't find `%s` action in logs." % action.short )
def setUp(self): super(TestActivityLogCount, self).setUp() now = datetime.now() bom = datetime(now.year, now.month, 1) self.lm = bom - timedelta(days=1) self.user = UserProfile.objects.get() amo.set_user(self.user)
def test_associate_acct_to_app_free_inapp(self): # Set up Solitude return values. api = self.sol.api # Set up Solitude return values. api.generic.product.get_object.side_effect = ObjectDoesNotExist api.generic.product.post.return_value = {'resource_uri': 'gpuri'} api.bango.product.get_object.side_effect = ObjectDoesNotExist api.bango.product.post.return_value = { 'resource_uri': 'bpruri', 'bango_id': 123} # Set up an existing bank account. user = UserProfile.objects.get(email=self.username) amo.set_user(user) seller = SolitudeSeller.objects.create( resource_uri='/path/to/sel', user=user) acct = PaymentAccount.objects.create( user=user, uri='asdf', name='test', inactive=False, solitude_seller=seller, bango_package_id=123, agreed_tos=True) # Associate account with app. self.make_premium(self.webapp) res = self.client.post( self.url, self.get_postdata({'price': 'free', 'allow_inapp': 'True', 'regions': ALL_PAID_REGION_IDS, 'accounts': acct.pk}), follow=True) self.assertNoFormErrors(res) eq_(res.status_code, 200) eq_(self.webapp.app_payment_account.payment_account.pk, acct.pk)
def notify_failed(file_pks, job_pk, data, **kw): log.info('[%s@None] Notifying failed for job %s.' % (len(file_pks), job_pk)) job = ValidationJob.objects.get(pk=job_pk) set_user(get_task_user()) for result in ValidationResult.objects.filter(validation_job=job, file__pk__in=file_pks): file = result.file version = file.version addon = version.addon context = get_context(addon, version, job, [result]) for author in addon.authors.all(): log.info(u'Emailing %s%s for addon %s, file %s about ' 'error from bulk validation job %s' % (author.email, ' [PREVIEW]' if data['preview_only'] else '', addon.pk, file.pk, job_pk)) args = (Template(data['subject']).render(context), Template(data['text']).render(context)) kwargs = dict(from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[author.email]) if data['preview_only']: job.preview_failure_mail(*args, **kwargs) else: send_mail(*args, **kwargs) amo.log(amo.LOG.BULK_VALIDATION_EMAILED, addon, version, details={'version': version.version, 'file': file.filename, 'target': job.target_version.version})
def find_abuse_escalations(addon_id, **kw): amo.set_user(get_task_user()) weekago = datetime.date.today() - datetime.timedelta(days=7) for abuse in AbuseReport.recent_high_abuse_reports(1, weekago, addon_id): if EscalationQueue.objects.filter(addon=abuse.addon).exists(): # App is already in the queue, no need to re-add it. # TODO: If not in queue b/c of abuse reports, add an # amo.LOG.ESCALATED_HIGH_ABUSE for reviewers. log.info(u'[addon:%s] High abuse reports, but already escalated' % (abuse.addon,)) continue # We have an abuse report and this add-on isn't currently in the # escalated queue... let's see if it has been detected and dealt with # already. logs = (AppLog.objects.filter( activity_log__action=amo.LOG.ESCALATED_HIGH_ABUSE.id, addon=abuse.addon).order_by('-created')) if logs: abuse_since_log = AbuseReport.recent_high_abuse_reports( 1, logs[0].created, addon_id) # If no abuse reports have happened since the last logged abuse # report, do not add to queue. if not abuse_since_log: log.info(u'[addon:%s] High abuse reports, but none since last ' 'escalation' % abuse.addon) continue # If we haven't bailed out yet, escalate this app. msg = u'High number of abuse reports detected' EscalationQueue.objects.create(addon=abuse.addon) amo.log(amo.LOG.ESCALATED_HIGH_ABUSE, abuse.addon, abuse.addon.current_version, details={'comments': msg}) log.info(u'[addon:%s] %s' % (abuse.addon, msg))
def setUp(self): super(TestAddonFromUpload, self).setUp() u = UserProfile.objects.get(pk=999) set_user(u) self.platform = Platform.objects.create(id=amo.PLATFORM_MAC.id) for version in ('3.0', '3.6.*'): AppVersion.objects.create(application_id=1, version=version)
def test_existing_account_should_be_disabled_for_non_owner(self): self.make_premium(self.webapp, price=self.price.price) acct, api, user = self.setup_payment_acct(make_owner=True) # Must be an app owner to change this. assert self.is_owner(user) # Associate account with app. res = self.client.post( self.url, self.get_postdata({'accounts': acct.pk, 'price': self.price.pk, 'regions': ALL_REGION_IDS}), follow=True) amo.set_user(self.other) # Make this user a dev so they have access to the payments page. AddonUser.objects.create(addon=self.webapp, user=self.other, role=amo.AUTHOR_ROLE_DEV) self.login(self.other) # Make sure not an owner. assert not self.is_owner(self.other) res = self.client.get(self.url) eq_(res.status_code, 200) pqr = pq(res.content) # No accounts setup. eq_(len(pqr('.no-accounts')), 1) # Currently associated account should be displayed separately. eq_(pqr('.current-account').text(), unicode(acct))
def test_rejected(self): comments = "oh no you di'nt!!" amo.set_user(UserProfile.objects.get(username='******')) amo.log(amo.LOG.REJECT_VERSION, self.webapp, self.webapp.current_version, user_id=999, details={'comments': comments, 'reviewtype': 'pending'}) self.webapp.update(status=amo.STATUS_REJECTED) (self.webapp.versions.latest() .all_files[0].update(status=amo.STATUS_DISABLED)) r = self.client.get(self.url) eq_(r.status_code, 200) doc = pq(r.content)('#version-status') eq_(doc('.status-rejected').length, 1) eq_(doc('#rejection').length, 1) eq_(doc('#rejection blockquote').text(), comments) my_reply = 'fixed just for u, brah' r = self.client.post(self.url, {'notes': my_reply, 'resubmit-app': ''}) self.assertRedirects(r, self.url, 302) webapp = self.get_webapp() eq_(webapp.status, amo.STATUS_PENDING, 'Reapplied apps should get marked as pending') eq_(webapp.versions.latest().all_files[0].status, amo.STATUS_PENDING, 'Files for reapplied apps should get marked as pending') eq_(unicode(webapp.versions.all()[0].approvalnotes), my_reply)
def wrapper(*args, **kw): old_user = get_user() set_user(get_task_user()) try: result = f(*args, **kw) finally: set_user(old_user) return result
def test_version_delete_logs(self): user = UserProfile.objects.get(pk=55021) amo.set_user(user) # The transform don't know bout my users. version = Version.objects.get(pk=81551) eq_(ActivityLog.objects.count(), 0) version.delete() eq_(ActivityLog.objects.count(), 2)
def process_request(self, request): """Attach authentication/permission helpers to request.""" request.check_ownership = partial(acl.check_ownership, request) # figure out our list of groups... if request.user.is_authenticated(): amo.set_user(request.user) request.groups = request.user.groups.all()
def test_delete_by(self): try: user = Addon.objects.get(id=3615).authors.all()[0] set_user(user) self.delete() assert 'DELETED BY: 55021' in mail.outbox[0].body finally: set_user(None)
def _post_teardown(self): amo.set_user(None) clean_translations(None) # Make sure queued translations are removed. # Make sure we revert everything we might have changed to prefixers. amo.urlresolvers.clean_url_prefixes() super(BaseTestCase, self)._post_teardown()
def notify_compatibility(users, job, data, **kw): log.info('[%s@%s] Sending notification mail for job %s.' % (len(users), notify_compatibility.rate_limit, job.pk)) set_user(get_task_user()) dry_run = data['preview_only'] app_id = job.target_version.application.pk stats = collections.defaultdict(int) stats['processed'] = 0 stats['is_dry_run'] = int(dry_run) for user in users: stats['processed'] += 1 for a in chain(user.passing_addons, user.failing_addons): results = job.result_set.filter(file__version__addon=a) a.links = ' '.join(absolutify(reverse('devhub.bulk_compat_result', args=[a.slug, r.pk])) for r in results) a.compat_link = absolutify(reverse('devhub.versions.edit', args=[a.pk, a.current_version.pk])) context = Context({ 'APPLICATION': str(job.application), 'VERSION': job.target_version.version, 'PASSING_ADDONS': user.passing_addons, 'FAILING_ADDONS': user.failing_addons, }) log.info(u'Emailing %s%s for %d addons about ' 'bulk validation job %s' % (user.email, ' [PREVIEW]' if dry_run else '', len(user.passing_addons) + len(user.failing_addons), job.pk)) args = (Template(data['subject']).render(context), Template(data['text']).render(context)) kwargs = dict(from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[user.email]) if dry_run: job.preview_notify_mail(*args, **kwargs) else: stats['author_emailed'] += 1 send_mail(*args, **kwargs) amo.log(amo.LOG.BULK_VALIDATION_USER_EMAILED, user, details={'passing': [a.id for a in user.passing_addons], 'failing': [a.id for a in user.failing_addons], 'target': job.target_version.version, 'application': app_id}) log.info('[%s@%s] bulk email stats for job %s: {%s}' % (len(users), notify_compatibility.rate_limit, job.pk, ', '.join('%s: %s' % (k, stats[k]) for k in sorted(stats.keys()))))
def test_set_task_user(self): @set_task_user def some_func(): return get_user() set_user(UserProfile.objects.get(username='******')) eq_(get_user().pk, 999) eq_(some_func().pk, int(settings.TASK_USER_ID)) eq_(get_user().pk, 999)
def setUp(self): self.addon = Addon.objects.get(pk=3615) category = Category.objects.get(pk=22) category.name = "test" category.save() self.data = {"summary": str(self.addon.summary), "name": str(self.addon.name), "slug": self.addon.slug} self.user = self.addon.authors.all()[0] amo.set_user(self.user)
def update_manifests(ids, **kw): task_log.info('[%s@%s] Update manifests.' % (len(ids), update_manifests.rate_limit)) # Since we'll be logging the updated manifest change to the users log, # we'll need to log in as user. amo.set_user(get_task_user()) for id in ids: _update_manifest(id)
def test_comm_thread_after_resubmission(self): self.create_switch("comm-dashboard") self.webapp.update(status=amo.STATUS_REJECTED) amo.set_user(UserProfile.objects.get(username="******")) (self.webapp.versions.latest().all_files[0].update(status=amo.STATUS_DISABLED)) my_reply = "no give up" self.client.post(self.url, {"notes": my_reply, "resubmit-app": ""}) notes = CommunicationNote.objects.all() eq_(notes.count(), 1) eq_(notes[0].body, my_reply)
def setUp(self): self.user = UserProfile.objects.filter()[0] amo.set_user(self.user) self.app = Addon.objects.get() self.app.premium_type = amo.ADDON_PREMIUM self.price = Price.objects.filter()[0] AddonPremium.objects.create(addon=self.app, price=self.price) self.seller = Mock(resource_uri='sellerres', user=self.user) self.account = Mock(user=self.user, name='paname', uri='acuri', inactive=False, seller_uri='selluri')
def test_unreviewed_addon(self): u = UserProfile.objects.get(email='*****@*****.**') addon = Addon.objects.all()[0] addon.status = amo.STATUS_UNREVIEWED c = u.favorites_collection() amo.set_user(u) c.add_addon(addon) self.client.login(username='******', password='******') response = self.client.get(c.get_url_path()) eq_(list(response.context['addons'].object_list), [addon])
def notify_success(version_pks, job_pk, data, **kw): log.info('[%s@%s] Updating max version for job %s.' % (len(version_pks), notify_success.rate_limit, job_pk)) job = ValidationJob.objects.get(pk=job_pk) set_user(get_task_user()) dry_run = data['preview_only'] stats = collections.defaultdict(int) stats['processed'] = 0 stats['is_dry_run'] = int(dry_run) for version in Version.objects.filter(pk__in=version_pks): stats['processed'] += 1 addon = version.addon file_pks = version.files.values_list('pk', flat=True) errors = (ValidationResult.objects.filter( validation_job=job, file__pk__in=file_pks).values_list('errors', flat=True)) if any(errors): stats['invalid'] += 1 log.info('Version %s for addon %s not updated, ' 'one of the files did not pass validation' % (version.pk, version.addon.pk)) continue app_flag = False for app in version.apps.filter( application=job.curr_max_version.application): if (app.max.version_int >= job.curr_max_version.version_int and app.max.version_int < job.target_version.version_int): stats['bumped'] += 1 log.info('Updating version %s%s for addon %s from version %s ' 'to version %s' % (version.pk, ' [DRY RUN]' if dry_run else '', version.addon.pk, job.curr_max_version.version, job.target_version.version)) app.max = job.target_version if not dry_run: app.save() app_flag = True else: stats['missed_targets'] += 1 log.info('Version %s for addon %s not updated, ' 'current max version is %s not %s' % (version.pk, version.addon.pk, app.max.version, job.curr_max_version.version)) if app_flag: results = job.result_set.filter(file__version=version) context = get_context(addon, version, job, results) for author in addon.authors.all(): log.info(u'Emailing %s%s for addon %s, version %s about ' 'success from bulk validation job %s' % (author.email, ' [PREVIEW]' if dry_run else '', addon.pk, version.pk, job_pk)) args = (Template(data['subject']).render(context), Template(data['text']).render(context)) kwargs = dict(from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[author.email]) if dry_run: job.preview_success_mail(*args, **kwargs) else: stats['author_emailed'] += 1 send_mail(*args, **kwargs) app_id = job.target_version.application.pk amo.log(amo.LOG.MAX_APPVERSION_UPDATED, version.addon, version, details={ 'version': version.version, 'target': job.target_version.version, 'application': app_id }) log.info('[%s@%s] bulk update stats for job %s: {%s}' % (len(version_pks), notify_success.rate_limit, job_pk, ', '.join( '%s: %s' % (k, stats[k]) for k in sorted(stats.keys()))))
def tearDown(self): amo.set_user(None) super(TestActivityLog, self).tearDown()
def setUp(self): super(TestActivityLog, self).setUp() u = UserProfile.objects.create(username='******') self.request = Mock() self.request.amo_user = self.user = u amo.set_user(u)
def setUp(self): """Start with one user, two add-ons.""" super(TestActivity, self).setUp() self.clone_addon(2) amo.set_user(self.user_profile) self.addon, self.addon2 = list(self.user_profile.addons.all())
def setUp(self): u = UserProfile.objects.create(username='******') amo.set_user(u)
def setUp(self): u = UserProfile.objects.create(username='******') self.request = Mock() self.request.amo_user = self.user = u amo.set_user(u)
def _post_teardown(self): amo.set_user(None) clean_translations(None) # Make sure queued translations are removed. super(TestCase, self)._post_teardown()
def setUp(self): self.user = UserProfile.objects.create(username='******', email='uh@hh') self.other = UserProfile.objects.exclude(id=self.user.id)[0] amo.set_user(self.user)
def notify_success(version_pks, job_pk, data, **kw): log.info('[%s@None] Updating max version for job %s.' % (len(version_pks), job_pk)) job = ValidationJob.objects.get(pk=job_pk) set_user(get_task_user()) for version in Version.objects.filter(pk__in=version_pks): addon = version.addon file_pks = version.files.values_list('pk', flat=True) errors = (ValidationResult.objects.filter( validation_job=job, file__pk__in=file_pks).values_list('errors', flat=True)) if any(errors): log.info('Version %s for addon %s not updated, ' 'one of the files did not pass validation' % (version.pk, version.addon.pk)) continue app_flag = False dry_run = data['preview_only'] for app in version.apps.filter( application=job.curr_max_version.application): if (app.max.version == job.curr_max_version.version and job.target_version.version != app.max.version): log.info('Updating version %s%s for addon %s from version %s ' 'to version %s' % (version.pk, ' [DRY RUN]' if dry_run else '', version.addon.pk, job.curr_max_version.version, job.target_version.version)) app.max = job.target_version if not dry_run: app.save() app_flag = True else: log.info('Version %s for addon %s not updated, ' 'current max version is %s not %s' % (version.pk, version.addon.pk, app.max.version, job.curr_max_version.version)) if app_flag: results = job.result_set.filter(file__version=version) context = get_context(addon, version, job, results) for author in addon.authors.all(): log.info(u'Emailing %s%s for addon %s, version %s about ' 'success from bulk validation job %s' % (author.email, ' [PREVIEW]' if dry_run else '', addon.pk, version.pk, job_pk)) args = (Template(data['subject']).render(context), Template(data['text']).render(context)) kwargs = dict(from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[author.email]) if dry_run: job.preview_success_mail(*args, **kwargs) else: send_mail(*args, **kwargs) amo.log(amo.LOG.BULK_VALIDATION_UPDATED, version.addon, version, details={ 'version': version.version, 'target': job.target_version.version })
def _post_teardown(self): amo.set_user(None) super(TestCase, self)._post_teardown()
def setUp(self): super(LogTest, self).setUp() u = UserProfile.objects.create(username='******') amo.set_user(u)
def setUp(self): now = datetime.now() bom = datetime(now.year, now.month, 1) self.lm = bom - timedelta(days=1) self.user = UserProfile.objects.get() amo.set_user(self.user)
def setUp(self): self.version_1_2_0 = 105387 self.addon = Addon.objects.get(pk=1865) set_user(None)
def process_response(self, request, response): amo.set_user(None) return response
def setUp(self): self.user = UserProfile.objects.create(username='******', email='uh@hh') amo.set_user(self.user)
def setUp(self): amo.set_user(UserProfile.objects.all()[0]) self.form = forms.AppFeaturesForm() self.app = Webapp.objects.get(pk=337141) self.features = self.app.current_version.features
def _user(self): """Create and return a user""" u = UserProfile.objects.create(username='******') amo.set_user(u) return u
def test_no_user(self): amo.set_user(None) count = ActivityLog.objects.count() amo.log(amo.LOG.CUSTOM_TEXT, 'hi') eq_(count, ActivityLog.objects.count())
"""Deleting add-ons is in fact soft deleting them, and emptying some of its fields with a unique constraint (like the slug). We now also empty the GUID field, to allow re-submitting those add-ons (once the GUID has been removed from the BlacklistedGuid through the admin. This migration empties all the previously soft deleted add-ons.""" from django.conf import settings import amo from addons.models import Addon from users.models import UserProfile addons = Addon.unfiltered.no_cache().filter(status=amo.STATUS_DELETED, guid__isnull=False) user = UserProfile.objects.get(pk=settings.TASK_USER_ID) amo.set_user(user) for addon in addons: amo.log(amo.LOG.DELETE_ADDON, addon.pk, addon.guid, addon, created=addon.modified) addon.guid = None addon.save()
def tearDown(self): amo.set_user(None)
def test_post_teardown(): amo.set_user(None) clean_translations(None) # Make sure queued translations are removed. # Make sure we revert everything we might have changed to prefixers. amo.urlresolvers.clean_url_prefixes()
def setUp(self): u = UserProfile(username='******') u.save() self.request = Mock() self.request.amo_user = self.user = u amo.set_user(u)
def process_exception(self, request, exception): amo.set_user(None)
def setUp(self): set_user(None)
def notify_compatibility_chunk(users, job, data, **kw): log.info('[%s@%s] Sending notification mail for job %s.' % (len(users), notify_compatibility.rate_limit, job.pk)) set_user(get_task_user()) dry_run = data['preview_only'] app_id = job.target_version.application stats = collections.defaultdict(int) stats['processed'] = 0 stats['is_dry_run'] = int(dry_run) for user in users: stats['processed'] += 1 try: for a in chain(user.passing_addons, user.failing_addons): try: results = job.result_set.filter(file__version__addon=a) a.links = [ absolutify( reverse('devhub.bulk_compat_result', args=[a.slug, r.pk])) for r in results ] v = a.current_version or a.latest_version a.compat_link = absolutify( reverse('devhub.versions.edit', args=[a.pk, v.pk])) except: task_error = sys.exc_info() log.error( u'Bulk validation email error for user %s, ' u'addon %s: %s: %s' % (user.email, a.slug, task_error[0], task_error[1]), exc_info=False) context = Context({ 'APPLICATION': unicode(amo.APP_IDS[job.application].pretty), 'VERSION': job.target_version.version, 'PASSING_ADDONS': user.passing_addons, 'FAILING_ADDONS': user.failing_addons, }) log.info( u'Emailing %s%s for %d addons about ' 'bulk validation job %s' % (user.email, ' [PREVIEW]' if dry_run else '', len(user.passing_addons) + len(user.failing_addons), job.pk)) args = (Template(data['subject']).render(context), Template(data['text']).render(context)) kwargs = dict(from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[user.email]) if dry_run: job.preview_notify_mail(*args, **kwargs) else: stats['author_emailed'] += 1 send_mail(*args, **kwargs) amo.log(amo.LOG.BULK_VALIDATION_USER_EMAILED, user, details={ 'passing': [a.id for a in user.passing_addons], 'failing': [a.id for a in user.failing_addons], 'target': job.target_version.version, 'application': app_id }) except: task_error = sys.exc_info() log.error(u'Bulk validation email error for user %s: %s: %s' % (user.email, task_error[0], task_error[1]), exc_info=False) log.info('[%s@%s] bulk email stats for job %s: {%s}' % (len(users), notify_compatibility.rate_limit, job.pk, ', '.join( '%s: %s' % (k, stats[k]) for k in sorted(stats.keys()))))
def setUp(self): self.addon = Addon.objects.create(type=amo.ADDON_EXTENSION) self.version = Version.objects.create(addon=self.addon) amo.set_user(UserProfile.objects.get(username='******'))