def email_plan_update(plan): recipients = get_plan_notification_recipients(plan) if len(recipients) == 0: return subject = u'TestPlan %s has been updated.' % plan.pk mailto(settings.PLAN_EMAIL_TEMPLATE, subject, recipients, context={'plan': plan})
def mail(self, template, subject, context = {}, to = [], request = None): from tcms.core.utils.mailto import mailto if not to: to = self.author.email to = list(set(to)) mailto(template, subject, to, context, request)
def notify_admins(sender, **kwargs): """ Very simple signal handler which sends emails to site admins when a new user has been registered! .. warning:: This handler isn't connected to the ``USER_REGISTERED_SIGNAL`` by default! """ from django.urls import reverse from django.conf import settings from django.utils.translation import ugettext_lazy as _ from tcms.core.utils.mailto import mailto from tcms.core.utils import request_host_link request = kwargs.get('request') user = kwargs.get('user') admin_emails = [] for _name, email in settings.ADMINS: admin_emails.append(email) user_url = request_host_link(request) + reverse('admin:auth_user_change', args=[user.pk]) mailto(template_name='email/user_registered/notify_admins.txt', recipients=admin_emails, subject=str(_('New user awaiting approval')), context={ 'username': user.username, 'user_url': user_url, })
def mail(self, template, subject, context={}, to=[], request=None): from tcms.core.utils.mailto import mailto if not to: to = self.author.email to = list(set(to)) mailto(template, subject, to, context, request)
def handle_emails_post_bug_save(sender, instance, created=False, **kwargs): from tcms.core.helpers.comments import get_comments from tcms.core.utils.mailto import mailto comments = get_comments(instance) recipients = set(comments.values_list("user_email", flat=True)) recipients.add(instance.reporter.email) if instance.assignee: recipients.add(instance.assignee.email) if not recipients: return mailto( template_name="email/post_bug_save/email.txt", recipients=list(recipients), subject=_("Bug #%(pk)d - %(summary)s") % { "pk": instance.pk, "summary": instance.summary }, context={ "bug": instance, "comment": comments.last(), }, )
def email_case_update(case): recipients = get_case_notification_recipients(case) if not recipients: return cc_list = case.emailing.get_cc_list() subject, body = history_email_for(case, case.summary) mailto(None, subject, recipients, body, cc=cc_list)
def email_plan_update(plan): recipients = get_plan_notification_recipients(plan) if not recipients: return subject = u'TestPlan %s has been updated.' % plan.pk mailto(settings.PLAN_EMAIL_TEMPLATE, subject, recipients, {'plan': plan})
def mail(self, template, subject, context, request=None): from tcms.core.utils.mailto import mailto to = [self.author.email] for dr in self.default_reviewer.all(): to.append(dr.email) mailto(template, subject, to, context, request)
def test_cc_email(self, mock): self.expected_recipients = ['*****@*****.**', '*****@*****.**'] mailto(template_name=None, subject='Test Subject', recipients='*****@*****.**', context='Body text', cc=['*****@*****.**']) mock.assert_called_once_with(**self.expected_kwargs)
def test_duplicate_recipients(self, mock): self.expected_recipients = ["*****@*****.**"] mailto( template_name=None, subject="Test Subject", recipients=["*****@*****.**", "*****@*****.**"], context="Body text", ) mock.assert_called_once_with(**self.expected_kwargs)
def test_admin_email_on_debug(self, mock): self.expected_recipients = ["*****@*****.**", "*****@*****.**"] mailto( template_name=None, subject="Test Subject", recipients="*****@*****.**", context="Body text", ) mock.assert_called_once_with(**self.expected_kwargs)
def _sendmail(self): mail_context = TestCase.mail_scene(objects=self._update_objects, field=self.target_field, value=self.new_value) if mail_context: from tcms.core.utils.mailto import mailto mail_context['context']['user'] = self.request.user mailto(**mail_context)
def email_case_deletion(case): recipients = get_case_notification_recipients(case) cc_list = case.emailing.get_cc_list() if not recipients: return subject = _('DELETED: TestCase #%(pk)d - %(summary)s') % {'pk': case.pk, 'summary': case.summary} context = {'case': case} mailto('email/post_case_delete/email.txt', subject, recipients, context, cc=cc_list)
def _sendmail(self): mail_context = TestCase.mail_scene(objects=self._update_objects, field=self.target_field) if mail_context: from tcms.core.utils.mailto import mailto mail_context['context']['user'] = self.request.user try: mailto(**mail_context) except Exception: # nosec:B110:try_except_pass pass
def email_case_deletion(case): recipients = get_case_notification_recipients(case) cc = case.emailing.get_cc_list() if not recipients: return subject = 'TestCase %s has been deleted.' % case.pk context = { 'case': case, } template = settings.CASE_EMAIL_TEMPLATE mailto(template, subject, recipients, context, cc=cc)
def _sendmail(self): mail_context = TestCase.mail_scene(objects=self._update_objects, field=self.target_field, value=self.new_value) if mail_context: from tcms.core.utils.mailto import mailto mail_context['request'] = self.request try: mailto(**mail_context) except: pass
def email_case_update(case): recipients = get_case_notification_recipients(case) if not recipients: return cc = case.emailing.get_cc_list() subject = 'TestCase %s has been updated.' % case.pk txt = case.latest_text() context = { 'test_case': case, 'test_case_text': txt, } template = settings.CASE_EMAIL_TEMPLATE mailto(template, subject, recipients, context, cc=cc)
def test_template(self, mock): template_name = 'email/user_registered/notify_admins.txt' context = { 'username': '******', 'user_url': 'https://example.com/username/', } self.expected_body = render_to_string(template_name, context) self.expected_recipients = ['*****@*****.**'] mailto(template_name=template_name, subject='Test Subject', recipients=['*****@*****.**'], context=context) mock.assert_called_once_with(**self.expected_kwargs)
def create_tenant(form_data, request): owner = request.user name = form_data['name'] schema_name = form_data['schema_name'] on_trial = form_data['on_trial'] paid_until = form_data['paid_until'] with schema_context('public'): tenant = Tenant.objects.create( name=name, schema_name=schema_name, paid_until=paid_until, on_trial=on_trial, owner=owner, organization=form_data['organization'], ) domain = Domain.objects.create( domain=tenant_domain(schema_name), is_primary=True, tenant=tenant, ) # work-around: for some reason the ContentType for tenant-user # relationship model doesn't get automatically created and if # the owner tries to add other authorized users via admin the # action will fail b/c ModelAdmin.log_addition tries to add a # a logging record linking to this content type and fails ! ContentType.objects.get_for_model(tenant.authorized_users.through) # make the owner the first authorized user # otherwise they can't login tenant.authorized_users.add(owner) with tenant_context(tenant): # this is used to build full URLs for things like emails site = Site.objects.get(pk=settings.SITE_ID) site.domain = domain.domain site.name = domain.domain site.save() mailto( template_name='tcms_tenants/email/new.txt', recipients=[owner.email], subject=str(_('New Kiwi TCMS tenant created')), context={ 'tenant_url': tenant_url(request, tenant.schema_name), } ) return tenant
def email_case_deletion(case): recipients = get_case_notification_recipients(case) cc_list = case.emailing.get_cc_list() if not recipients: return subject = _("DELETED: TestCase #%(pk)d - %(summary)s") % { "pk": case.pk, "summary": case.summary, } context = {"case": case} mailto("email/post_case_delete/email.txt", subject, recipients, context, cc=cc_list)
def handle_emails_post_bug_save(sender, instance, created=False, **kwargs): """ Send email updates to assignee after they've been assigned a bug on bug creation. """ if not created or instance.assignee is None: return from tcms.core.utils.mailto import mailto mailto(template_name='email/post_bug_save/email.txt', recipients=[instance.assignee.email], subject=_('NEW: Bug #{} - {}').format(instance.pk, instance.summary), context={'bug': instance})
def test_template(self, mock): template_name = "email/user_registered/notify_admins.txt" context = { "username": "******", "user_url": "https://example.com/username/", } self.expected_body = render_to_string(template_name, context) self.expected_recipients = ["*****@*****.**"] mailto( template_name=template_name, subject="Test Subject", recipients=["*****@*****.**"], context=context, ) mock.assert_called_once_with(**self.expected_kwargs)
def send_confirm_mail(self, request, activation_key): current_site = Site.objects.get(pk=settings.SITE_ID) confirm_url = '%s%s' % ( request_host_link(request, current_site.domain), reverse('tcms-confirm', args=[ activation_key.activation_key, ])) mailto(template_name='email/confirm_registration.txt', recipients=self.cleaned_data['email'], subject=_('Your new %s account confirmation') % current_site.domain, context={ 'user': self.instance, 'site_domain': current_site.domain, 'confirm_url': confirm_url, })
def send_confirm_mail(self, request, activation_key, template_name='registration/confirm_email.html'): current_site = Site.objects.get_current() confirm_url = '%s%s' % ( request_host_link(request, current_site.domain), reverse('tcms-confirm', args=[activation_key.activation_key, ]) ) mailto( template_name=template_name, recipients=self.cleaned_data['email'], subject='Your new %s account confirmation' % current_site.domain, context={ 'user': self.instance, 'site': current_site, 'active_key': activation_key, 'confirm_url': confirm_url, } )
def handle_emails_post_bug_save(sender, instance, created=False, **kwargs): """ Send email updates to assignee after they've been assigned a bug on bug creation. """ if not created or instance.assignee is None: return from tcms.core.utils.mailto import mailto mailto( template_name="email/post_bug_save/email.txt", recipients=[instance.assignee.email], subject=_("NEW: Bug #%(pk)d - %(summary)s") % { "pk": instance.pk, "summary": instance.summary }, context={"bug": instance}, )
def send_confirm_mail(self, request, activation_key): current_site = Site.objects.get(pk=settings.SITE_ID) confirm_url = request_host_link(request, current_site.domain) + reverse( "tcms-confirm", args=[ activation_key.activation_key, ], ) mailto( template_name="email/confirm_registration.txt", recipients=self.cleaned_data["email"], subject=_("Your new %s account confirmation") % current_site.domain, context={ "user": self.instance, "site_domain": current_site.domain, "confirm_url": confirm_url, }, )
def notify_admins(sender, **kwargs): """ Very simple signal handler which sends emails to site admins when a new user has been registered! .. warning:: This handler isn't connected to the ``USER_REGISTERED_SIGNAL`` by default! """ from django.conf import settings from django.contrib.auth import get_user_model from django.urls import reverse from tcms.core.utils import request_host_link from tcms.core.utils.mailto import mailto if kwargs.get("raw", False): return admin_emails = set() # super-users can approve others for super_user in get_user_model().objects.filter(is_superuser=True): admin_emails.add(super_user.email) # site admins should be able to do so as well for _name, email in settings.ADMINS: admin_emails.add(email) request = kwargs.get("request") user = kwargs.get("user") user_url = request_host_link(request) + reverse("admin:auth_user_change", args=[user.pk]) mailto( template_name="email/user_registered/notify_admins.txt", recipients=list(admin_emails), subject=str(_("New user awaiting approval")), context={ "username": user.username, "user_url": user_url, }, )
def handle_emails_post_run_save(sender, *_args, **kwargs): """ Send email updates after a TestRus has been created or updated! """ from tcms.core.history import history_email_for from tcms.core.utils.mailto import mailto instance = kwargs['instance'] if kwargs.get('created'): template_name = 'email/post_run_save/email.txt' subject = _('NEW: TestRun #%(pk)d - %(summary)s') % { 'pk': instance.pk, 'summary': instance.summary } context = {'test_run': instance} else: template_name = None subject, context = history_email_for(instance, instance.summary) mailto(template_name, subject, instance.get_notify_addrs(), context)
def send_confirm_mail(self, request, active_key, template_name='registration/confirm_email.html'): from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from tcms.core.utils.mailto import mailto from tcms.core.utils import request_host_link s = Site.objects.get_current() cu = '%s%s' % ( request_host_link(request, s.domain), reverse('nitrate-activation-confirm', args=[active_key.activation_key]) ) mailto( template_name=template_name, to_mail=self.cleaned_data['email'], subject='Your new %s account confirmation' % s.domain, context={ 'user': self.instance, 'site': s, 'active_key': active_key, 'confirm_url': cu, } )
def send_confirm_mail(self, request, active_key, template_name='registration/confirm_email.html'): from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from tcms.core.utils.mailto import mailto from tcms.core.utils import request_host_link s = Site.objects.get_current() cu = '%s%s' % (request_host_link(request, s.domain), reverse('nitrate-activation-confirm', args=[active_key.activation_key])) mailto(template_name=template_name, to_mail=self.cleaned_data['email'], subject='Your new %s account confirmation' % s.domain, context={ 'user': self.instance, 'site': s, 'active_key': active_key, 'confirm_url': cu, })
def handle_emails_post_run_save(sender, *_args, **kwargs): """ Send email updates after a TestRus has been created or updated! """ from django.utils.translation import gettext as _ from tcms.core.utils.mailto import mailto instance = kwargs['instance'] if kwargs.get('created'): subject = _('New TestRun %(summary)s created') % { 'summary': instance.summary } else: subject = _('TestRun %(summary)s has been updated') % { 'summary': instance.summary } mailto(template_name='email/post_run_save/email.txt', subject=subject, recipients=instance.get_notify_addrs(), context={'test_run': instance})
def invite_users(request, email_addresses): for email in email_addresses: # note: users are on public_schema user = UserModel.objects.filter(email=email).first() # email not found, need to create account for them if not user: user = create_user_account(email) # user already authorized for tenant if request.tenant.authorized_users.filter(pk=user.pk).exists(): continue request.tenant.authorized_users.add(user) mailto(template_name='tcms_tenants/email/invite_user.txt', recipients=[user.email], subject=str(_('Invitation to join Kiwi TCMS')), context={ "invited_by": request.user.get_full_name() or request.user.username, "tenant_url": tenant_url(request, request.tenant.schema_name), })
def handle_emails_post_run_save(sender, *_args, **kwargs): """ Send email updates after a TestRus has been created or updated! """ from tcms.core.history import history_email_for from tcms.core.utils.mailto import mailto if kwargs.get("raw", False): return instance = kwargs["instance"] if kwargs.get("created"): template_name = "email/post_run_save/email.txt" subject = _("NEW: TestRun #%(pk)d - %(summary)s") % { "pk": instance.pk, "summary": instance.summary, } context = {"test_run": instance} else: template_name = None subject, context = history_email_for(instance, instance.summary) mailto(template_name, subject, instance.get_notify_addrs(), context)
def update_case_status(request): ''' Update Test Case Status, return Plan's case count in json for update in real-time. ''' error = None now = datetime.datetime.now() data = request.REQUEST.copy() plan_id = data.get('plan_id') ctype = data.get("content_type") vtype = data.get('value_type', 'str') object_pk_str = data.get("object_pk") field = data.get('field') value = data.get('value') object_pk = [int(a) for a in object_pk_str.split(',')] if not field or not value or not object_pk or not ctype: return say_no('Following fields are required - content_type, object_pk, field and value.') # Convert the value type # FIXME: Django bug here: update() keywords must be strings field = str(field) value, error = get_value_by_type(value, vtype) if error: return say_no(error) has_perms = check_permission(request,ctype) if not has_perms: return say_no('Permission Dinied.') model = models.get_model(*ctype.split(".", 1)) targets = model._default_manager.filter(pk__in=object_pk) if not targets: return say_no('No record found') if not hasattr(targets[0], field): return say_no('%s has no field %s' % (ctype, field)) if hasattr(targets[0], 'log_action'): for t in targets: try: t.log_action( who = request.user, action = 'Field %s changed from %s to %s.' % ( field, getattr(t, field), value ) ) except (AttributeError, User.DoesNotExist): pass targets.update(**{field: value}) if hasattr(model, 'mail_scene'): from tcms.core.utils.mailto import mailto mail_context = model.mail_scene( objects = targets, field = field, value = value, ctype = ctype, object_pk = object_pk, ) if mail_context: mail_context['request'] = request try: mailto(**mail_context) except: pass try: plan = TestPlan.objects.get(plan_id=plan_id) except Exception, e: return say_no("No plan record found.")
def update_case_run_status(request): ''' Update Case Run status. ''' error = None now = datetime.datetime.now() data = request.REQUEST.copy() ctype = data.get("content_type") vtype = data.get('value_type', 'str') object_pk_str = data.get("object_pk") field = data.get('field') value = data.get('value') object_pk = [int(a) for a in object_pk_str.split(',')] if not field or not value or not object_pk or not ctype: return say_no('Following fields are required - content_type, object_pk, field and value.') # Convert the value type # FIXME: Django bug here: update() keywords must be strings field = str(field) value, error = get_value_by_type(value, vtype) if error: return say_no(error) has_perms = check_permission(request,ctype) if not has_perms: return say_no('Permission Dinied.') model = models.get_model(*ctype.split(".", 1)) targets = model._default_manager.filter(pk__in=object_pk) if not targets: return say_no('No record found') if not hasattr(targets[0], field): return say_no('%s has no field %s' % (ctype, field)) if hasattr(targets[0], 'log_action'): for t in targets: try: t.log_action( who = request.user, action = 'Field %s changed from %s to %s.' % ( field, getattr(t, field), value ) ) except (AttributeError, User.DoesNotExist): pass objects_update(targets, **{field:value}) if hasattr(model, 'mail_scene'): from tcms.core.utils.mailto import mailto mail_context = model.mail_scene( objects = targets, field = field, value = value, ctype = ctype, object_pk = object_pk, ) if mail_context: mail_context['request'] = request try: mailto(**mail_context) except: pass # Special hacking for updating test case run status # https://bugzilla.redhat.com/show_bug.cgi?id=658160 if ctype == 'testruns.testcaserun' and field == 'case_run_status': if len(targets) == 1: targets[0].set_current() for t in targets: field = 'close_date' t.log_action( who = request.user, action = 'Field %s changed from %s to %s.' % ( field, getattr(t, field), now ) ) if t.tested_by != request.user: field = 'tested_by' t.log_action( who = request.user, action = 'Field %s changed from %s to %s.' % ( field, getattr(t, field), request.user ) ) field = 'assignee' try: assignee = t.assginee if assignee != request.user: t.log_action( who = request.user, action = 'Field %s changed from %s to %s.' % ( field, getattr(t, field), request.user ) ) #t.assignee = request.user t.save() except (AttributeError, User.DoesNotExist): pass targets.update(close_date=now, tested_by=request.user) run_status_count = targets[0].run.case_run_status.split(',') complete_count = 0 failed_count = 0 total_count = 0 f_ids = TestCaseRunStatus._get_failed_status_ids() c_ids = TestCaseRunStatus._get_completed_status_ids() try: for status_count in run_status_count: s_id, s_count = status_count.split(':') s_id = int(s_id) s_count = int(s_count) if s_id in c_ids: complete_count += s_count if s_id in f_ids: failed_count += s_count total_count += s_count except Exception, e: return say_no(str(e))
def create_tenant(form, request): with schema_context('public'): # If a schema with name "empty" exists then use it for # cloning b/c that's faster if Tenant.objects.filter(schema_name='empty').first(): schema_name = form.cleaned_data["schema_name"] paid_until = form.cleaned_data["paid_until"] or datetime.datetime( 3000, 3, 31) call_command( "clone_tenant", "--clone_from", "empty", "--clone_tenant_fields", False, "--schema_name", schema_name, "--name", form.cleaned_data["name"], "--paid_until", paid_until, "--publicly_readable", form.cleaned_data["publicly_readable"], "--owner_id", request.user.pk, "--organization", form.cleaned_data["organization"] or "-", "--domain-domain", tenant_domain(schema_name), "--domain-is_primary", True, ) tenant = Tenant.objects.get(schema_name=schema_name) if not form.cleaned_data["paid_until"]: tenant.paid_until = None tenant.save() if not form.cleaned_data["organization"]: tenant.organization = "" tenant.save() domain = tenant.domains.first() else: # otherwise default to applying all migrations one by one tenant = form.save() domain = Domain.objects.create( domain=tenant_domain(tenant.schema_name), is_primary=True, tenant=tenant, ) # work-around: for some reason the ContentType for tenant-user # relationship model doesn't get automatically created and if # the owner tries to add other authorized users via admin the # action will fail b/c ModelAdmin.log_addition tries to add a # a logging record linking to this content type and fails ! ContentType.objects.get_for_model(tenant.authorized_users.through) # make the owner the first authorized user # otherwise they can't login tenant.authorized_users.add(tenant.owner) with tenant_context(tenant): # this is used to build full URLs for things like emails site = Site.objects.get(pk=settings.SITE_ID) site.domain = domain.domain site.name = domain.domain site.save() mailto(template_name='tcms_tenants/email/new.txt', recipients=[tenant.owner.email], subject=str(_('New Kiwi TCMS tenant created')), context={ 'tenant_url': tenant_url(request, tenant.schema_name), }) return tenant
def update_case_run_status(request): """Update Case Run status.""" now = datetime.datetime.now() data = request.POST.copy() ctype = data.get("content_type") vtype = data.get('value_type', 'str') object_pk_str = data.get("object_pk") field = data.get('field') value = data.get('value') object_pk = [int(a) for a in object_pk_str.split(',')] if not field or not value or not object_pk or not ctype: return say_no( 'Following fields are required - content_type, ' 'object_pk, field and value.') # Convert the value type # FIXME: Django bug here: update() keywords must be strings field = str(field) value, error = get_value_by_type(value, vtype) if error: return say_no(error) has_perms = check_permission(request, ctype) if not has_perms: return say_no('Permission Dinied.') model = utils.get_model(ctype) targets = model._default_manager.filter(pk__in=object_pk) if not targets: return say_no('No record found') if not hasattr(targets[0], field): return say_no('%s has no field %s' % (ctype, field)) if hasattr(targets[0], 'log_action'): for t in targets: try: t.log_action( who=request.user, field=field, original_value=getattr(t, field), new_value=TestCaseRunStatus.id_to_name(value)) except (AttributeError, User.DoesNotExist): pass objects_update(targets, **{field: value}) if hasattr(model, 'mail_scene'): from tcms.core.utils.mailto import mailto mail_context = model.mail_scene( objects=targets, field=field, value=value, ctype=ctype, object_pk=object_pk, ) if mail_context: mail_context['context']['user'] = request.user mailto(**mail_context) # Special hacking for updating test case run status if ctype == 'testruns.testcaserun' and field == 'case_run_status': for t in targets: field = 'close_date' t.log_action( who=request.user, field=field, original_value=getattr(t, field) or '', new_value=now) if t.tested_by != request.user: field = 'tested_by' t.log_action( who=request.user, field=field, original_value=getattr(t, field) or '', new_value=request.user) field = 'assignee' try: assignee = t.assginee if assignee != request.user: t.log_action( who=request.user, field=field, original_value=getattr(t, field) or '', new_value=request.user) # t.assignee = request.user t.save() except (AttributeError, User.DoesNotExist): pass targets.update(close_date=now, tested_by=request.user) return HttpResponse(json.dumps({'rc': 0, 'response': 'ok'}))
def mail(self, template, subject, context, to=[], request=None): from tcms.core.utils.mailto import mailto to = self.get_notify_addrs() mailto(template, subject, to, context, request)
def update(request): ''' Generic approach to update a model,\n based on contenttype. ''' now = datetime.datetime.now() data = request.REQUEST.copy() ctype = data.get("content_type") vtype = data.get('value_type', 'str') object_pk_str = data.get("object_pk") field = data.get('field') value = data.get('value') object_pk = [int(a) for a in object_pk_str.split(',')] if not field or not value or not object_pk or not ctype: return say_no( 'Following fields are required - content_type, ' 'object_pk, field and value.') # Convert the value type # FIXME: Django bug here: update() keywords must be strings field = str(field) value, error = get_value_by_type(value, vtype) if error: return say_no(error) has_perms = check_permission(request, ctype) if not has_perms: return say_no('Permission Dinied.') model = models.get_model(*ctype.split(".", 1)) targets = model._default_manager.filter(pk__in=object_pk) if not targets: return say_no('No record found') if not hasattr(targets[0], field): return say_no('%s has no field %s' % (ctype, field)) if hasattr(targets[0], 'log_action'): for t in targets: try: t.log_action( who=request.user, action='Field %s changed from %s to %s.' % ( field, getattr(t, field), value ) ) except (AttributeError, User.DoesNotExist): pass objects_update(targets, **{field: value}) if hasattr(model, 'mail_scene'): mail_context = model.mail_scene( objects=targets, field=field, value=value, ctype=ctype, object_pk=object_pk, ) if mail_context: from tcms.core.utils.mailto import mailto mail_context['context']['user'] = request.user try: mailto(**mail_context) except: pass # Special hacking for updating test case run status if ctype == 'testruns.testcaserun' and field == 'case_run_status': for t in targets: field = 'close_date' t.log_action( who=request.user, action='Field %s changed from %s to %s.' % ( field, getattr(t, field), now ) ) if t.tested_by != request.user: field = 'tested_by' t.log_action( who=request.user, action='Field %s changed from %s to %s.' % ( field, getattr(t, field), request.user ) ) field = 'assignee' try: assignee = t.assginee if assignee != request.user: t.log_action( who=request.user, action='Field %s changed from %s to %s.' % ( field, getattr(t, field), request.user ) ) # t.assignee = request.user t.save() except (AttributeError, User.DoesNotExist): pass targets.update(close_date=now, tested_by=request.user) return say_yes()
def update_case_status(request): ''' Update Test Case Status, return Plan's case count in json for update in real-time. ''' data = request.REQUEST.copy() plan_id = data.get('plan_id') ctype = data.get("content_type") vtype = data.get('value_type', 'str') object_pk_str = data.get("object_pk") field = data.get('field') value = data.get('value') object_pk = [int(a) for a in object_pk_str.split(',')] if not field or not value or not object_pk or not ctype: return say_no( 'Following fields are required - content_type, ' 'object_pk, field and value.') # Convert the value type # FIXME: Django bug here: update() keywords must be strings field = str(field) value, error = get_value_by_type(value, vtype) if error: return say_no(error) has_perms = check_permission(request, ctype) if not has_perms: return say_no('Permission Dinied.') model = models.get_model(*ctype.split(".", 1)) targets = model._default_manager.filter(pk__in=object_pk) if not targets: return say_no('No record found') if not hasattr(targets[0], field): return say_no('%s has no field %s' % (ctype, field)) if hasattr(targets[0], 'log_action'): for t in targets: try: t.log_action( who=request.user, action='Field %s changed from %s to %s.' % ( field, getattr(t, field), value ) ) except (AttributeError, User.DoesNotExist): pass targets.update(**{field: value}) if hasattr(model, 'mail_scene'): from tcms.core.utils.mailto import mailto mail_context = model.mail_scene( objects=targets, field=field, value=value, ctype=ctype, object_pk=object_pk, ) if mail_context: mail_context['context']['user'] = request.user try: mailto(**mail_context) except: pass try: plan = TestPlan.objects.get(plan_id=plan_id) except Exception: return say_no("No plan record found.") # Initial the case counter confirm_status_name = 'CONFIRMED' plan.run_case = plan.case.filter(case_status__name=confirm_status_name) plan.review_case = plan.case.exclude(case_status__name=confirm_status_name) run_case_count = plan.run_case.count() case_count = plan.case.count() # FIXME: why not calculate review_case_count or run_case_count by using # substraction, which saves one SQL query. review_case_count = plan.review_case.count() return HttpResponse( simplejson.dumps({ 'rc': 0, 'response': 'ok', 'run_case_count': run_case_count, 'case_count': case_count, 'review_case_count': review_case_count }) )