Пример #1
0
    def setUp(self):
        self.year = Year.objects.create(start_year=2016)
        self.group = Group.objects.create(name='name_groups', year=self.year)
        self.course = Course.objects.create(name='course_name', year=self.year)
        self.course.groups = [self.group]
        self.course.save()

        self.task = Task.objects.create(title='task',
                                        course=self.course,
                                        problem_id="A")
        self.student = User.objects.create_user(username='******',
                                                password='******')
        self.responsible = User.objects.create_user(username='******',
                                                    password='******')

        status = IssueStatus.objects.get(tag=Issue.STATUS_ACCEPTED)

        self.issue = Issue()
        self.issue.student = self.student
        self.issue.task = self.task
        self.issue.responsible = self.responsible
        self.issue.status_field = status
        self.issue.save()
        self.issue.save()
        self.issue_id = self.issue.id
Пример #2
0
 def testIssueNotification(self):
     user = create_user()
 
     issue = Issue()
     issue.description = "This is a test"
     issue.save()
     
     assert Issue.all().count() == 1
Пример #3
0
def issue_by_number(pk):
    """ Get's the issue by a primary key or a number, i like hacking the url so
        you can just put in a number in the URL """
    number = safe_int(pk)
    if number:
        issues = Issue.all().filter("number = ", number)
        return issues[0]
    else:
        return Issue.get(pk)
Пример #4
0
def issue_by_number(pk):
    """ Get's the issue by a primary key or a number, i like hacking the url so
        you can just put in a number in the URL """
    number = safe_int(pk)
    if number:
        issues = Issue.all().filter("number = ", number)
        return issues[0]
    else:
        return Issue.get(pk)
Пример #5
0
    def testIssueURL(self):
        self._setup()

        self.issue = Issue()
        self.issue.description = "This is a test"
        self.issue.project = self.project
        self.issue.save()

        assert self.issue.issueprojecturl_set.count() == 2
        assert self.issue.issueprojecturl_set[0].status == "not_fixed"
Пример #6
0
 def setUp(self) -> None:
     self.issue = Issue(
         number=1,
         name='any title',
         body='any body',
         main_language=ProgrammingLanguage.get_other_default_language(),
         repository=Repository.objects.create(
             name='iwannacontrib-issues-test-integration-test',
             owner=Owner.objects.create(owner='carlosmaniero')))
     self.issue.save()
Пример #7
0
def create(request):
    sunetid = request.user.webauth_username
    attrs = request.POST.copy()
    if len(attrs) == 0 or 'kind' not in attrs:
        return HttpResponseNotFound("The form did not submit correctly. Please try again.")
    new_issue = Issue(kind=attrs['kind'], sunetid1=sunetid).get_typed()
    form = form_class_for_issue(new_issue)(attrs, instance=new_issue)
    if form.is_valid() and new_issue.can_declare():
        form.save()
        return HttpResponseRedirect(reverse('issues.views.manage_index'))
    else:
        return render_to_response('issues/manage/new.html', {'new_issue': new_issue, 'form': form,'error': True}, context_instance=RequestContext(request))
Пример #8
0
 def test_get_add_vote_to_cart(self):
     feature = Issue(
         issue_type='feature',
         title='new feature 1',
         description='this will be great',
         author=self.user,
     )
     feature.save()
     response = self.client.get(
         reverse('add_vote_to_cart', args=[feature.id]))
     self.assertEqual(response.status_code, 302)
     self.assertRedirects(response, reverse('view_cart'))
Пример #9
0
 def delete(self, *args, **kwargs):
     """docstring for delete"""
     from issues.models import Issue
     from resources.models import Resource, Curation
     res = Resource.objects(owner=self)
     curs = Curation.objects(owner=self)
     if curs.count() or res.count():
         raise Exception('This account owns resources/curations.')
     Collection.objects(owner=self).delete()
     Issue.objects(reporter=self).delete()
     User.objects.get(pk=self.local_id).delete()
     self.reindex(remove=True)
     super(Account, self).delete(*args, **kwargs)
Пример #10
0
 def delete(self, *args, **kwargs):
     """docstring for delete"""
     from issues.models import Issue
     from resources.models import Resource, Curation
     res = Resource.objects(owner=self)
     curs = Curation.objects(owner=self)
     if curs.count() or res.count():
         raise Exception('This account owns resources/curations.')
     Collection.objects(owner=self).delete()
     Issue.objects(reporter=self).delete()
     User.objects.get(pk=self.local_id).delete()
     self.reindex(remove=True)
     super(Account, self).delete(*args, **kwargs)
Пример #11
0
 def setUp(self):
     self.client = Client()
     self.user = User.objects.create_user('testuser', '*****@*****.**',
                                          'testpassword')
     self.client.login(username='******', password='******')
     self.open_bug = Issue(issue_type='bug',
                           title='testbug1',
                           description='testdescription1',
                           author=self.user)
     self.open_bug.save()
     self.open_feature = Issue(issue_type='feature',
                               title='testfeature1',
                               description='testdescription1',
                               author=self.user)
     self.open_feature.save()
     self.closed_bug = Issue(issue_type='bug',
                             title='testbug2',
                             description='testdescription2',
                             author=self.user,
                             status='closed')
     self.closed_bug.save()
     self.closed_bug.date_complete = timezone.now()
     self.closed_bug.save()
     self.closed_feature = Issue(issue_type='feature',
                                 title='testfeature2',
                                 description='testdescription2',
                                 author=self.user,
                                 status='closed')
     self.closed_feature.save()
     self.closed_feature.date_complete = timezone.now()
     self.closed_feature.save()
Пример #12
0
 def sync(self, tracker):
     server = ServerProxy(tracker.config,
                          allow_none=True,
                          use_datetime=datetime)
     last_update = DateTime(time.mktime(tracker.last_update.timetuple()))
     users = self._get_users(server)
     ids = map(int,
               server.filter('issue', None, {'activity': str(last_update)}))
     for issue_id in ids:
         data = server.display('issue%d' % issue_id, 'title', 'creation',
                               'creator', 'assignedto', 'activity',
                               'messages', 'status')
         issue = Issue.by_tracker_id(tracker.id, issue_id)
         issue.no = issue_id
         issue.set_title(data.get('title', ''))
         issue.set_description(
             self._get_description(server, data.get('messages', [])))
         issue.reporter = users[int(data['creator'])]
         issue.owner = users[int(data['assignedto'])]
         issue.last_change = _roundup_date_to_datetime(data.get('activity'))
         status = int(data.get('status', -1))
         issue.active = status in ACTIVE_STATUS
         issue.tracker = tracker
         if not issue.id:
             issue.created = datetime.now()
         issue.updated = datetime.now()
         issue.save()
         post_issue_sync.send(sender=self, issue=issue)
         self._update_user_data(server, data, issue, users)
     tracker.last_update = datetime.now() - timedelta(days=1)
     tracker.save()
     post_tracker_sync.send(sender=self, tracker=tracker)
     return True
Пример #13
0
 def sync(self, tracker):
     server = ServerProxy(tracker.config, allow_none=True,
                          use_datetime=datetime)
     last_update = DateTime(time.mktime(tracker.last_update.timetuple()))
     users = self._get_users(server)
     ids = map(int, server.filter('issue', None, {'activity':
                                                  str(last_update)}))
     for issue_id in ids:
         data = server.display('issue%d' % issue_id, 'title', 'creation',
                               'creator', 'assignedto', 'activity',
                               'messages', 'status')
         issue = Issue.by_tracker_id(tracker.id, issue_id)
         issue.no = issue_id
         issue.set_title(data.get('title', ''))
         issue.set_description(self._get_description(
             server, data.get('messages', [])))
         issue.reporter = users[int(data['creator'])]
         issue.owner = users[int(data['assignedto'])]
         issue.last_change = _roundup_date_to_datetime(data.get('activity'))
         status = int(data.get('status', -1))
         issue.active = status in ACTIVE_STATUS
         issue.tracker = tracker
         if not issue.id:
             issue.created = datetime.now()
         issue.updated = datetime.now()
         issue.save()
         post_issue_sync.send(sender=self, issue=issue)
         self._update_user_data(server, data, issue, users)
     tracker.last_update = datetime.now() - timedelta(days=1)
     tracker.save()
     post_tracker_sync.send(sender=self, tracker=tracker)
     return True
Пример #14
0
 def setUp(self):
     for issue in Issue.all(): issue.delete()
     for log in Log.all(): log.delete()
     for comment in Comment.all(): comment.delete()
     for group in Group.all(): group.delete()
     for error in Error.all(): error.delete()
     for project in Project.all(): project.delete()
Пример #15
0
def edit_project_url(request, pk):
    issue = Issue.get(pk)
    urls = IssueProjectURL.all().filter("issue = ", issue)
    url_ids = dict([(url.id, url) for url in urls])
    if request.POST:
        for key, value in request.POST.items():
            if key in url_ids:
                assert value in [ i[0] for i in issue_project_url_statuses ], \
                    "%s not in %s" % (value, issue_project_url_statuses)
                url_ids[key].status = value
                url_ids[key].save()
        return HttpResponseRedirect(reverse("issues-view", args=[
            pk,
        ]))
    return direct_to_template(request,
                              "issue_project_url.html",
                              extra_context={
                                  "issue": issue,
                                  "urls": urls,
                                  "issue_project_url_statuses":
                                  issue_project_url_statuses,
                                  "nav": {
                                      "selected": "issues",
                                  },
                              })
Пример #16
0
def create_issue(request):
    return Issue(title=request.POST['title'],
                 description=request.POST['description'],
                 latitude=request.POST['latitude'],
                 longitude=request.POST['longitude'],
                 tags=request.POST['tags'],
                 reporter=request.user)
Пример #17
0
    def setUp(self):
        self.year = Year.objects.create(start_year=2016)
        self.group = Group.objects.create(name='name_groups', year=self.year)
        self.course = Course.objects.create(name='course_name',
                                            year=self.year)
        self.course.groups = [self.group]
        self.course.save()

        self.task = Task.objects.create(title='task',
                                        course=self.course,
                                        problem_id="A")
        self.student = User.objects.create_user(username='******',
                                                password='******')
        self.responsible = User.objects.create_user(username='******',
                                                    password='******')

        status = IssueStatus.objects.get(tag=Issue.STATUS_ACCEPTED)

        self.issue = Issue()
        self.issue.student = self.student
        self.issue.task = self.task
        self.issue.responsible = self.responsible
        self.issue.status_field = status
        self.issue.save()
        self.issue.save()
        self.issue_id = self.issue.id
Пример #18
0
    def test_vote_proposal(self):
#        p = self.test_create_proposal()
        ######################################
        i = Issue(community=self.community, title="Issue ABC",
            created_by=self.chairmen[0])
        i.full_clean()
        i.save()
        title = 'Proposal XYZ'
        content = 'hellow world'
        p = Proposal.objects.create(type=ProposalType.RULE, issue=i, created_by=self.chairmen[0], title=title, content=content)
        ######################################
        #TODO: create this via HTML request
        pv = ProposalVote(proposal=p, user=self.members[0], value=ProposalVoteValue.CON)
        pv.full_clean()
        pv.save()
        return pv
    def handle(self, count, service, min_lat=None, max_lat=None, min_lon=None, max_lon=None, **options):
        service = Service.objects.get(service_code=service)
        for i in range(count):
            lat = long = None
            if min_lat and max_lat and min_lon and max_lon:
                lat = random.uniform(min_lat, max_lat)
                long = random.uniform(min_lon, max_lon)

            issue = Issue(
                service=service,
                lat=lat,
                long=long,
                submitter_email='*****@*****.**',
                description=generate_description(),
            )
            issue.save()
        self.stdout.write('{} issues created'.format(count))
Пример #20
0
    def test_get_or_create_anonymously(self):
        client = self.client

        # get get_or_create page
        response = client.get(reverse('issues.views.get_or_create',
                                      kwargs={'task_id': self.task.id, 'student_id': self.student.id}))
        self.assertEqual(response.status_code, 302, "Need login for get_or_create")

        issue = Issue()
        issue.student = self.student
        issue.task = self.task
        issue.save()

        # get issue_page page
        response = client.get(reverse('issues.views.issue_page',
                                      kwargs={'issue_id': issue.id}))
        self.assertEqual(response.status_code, 302, "Need login for issue_page")
Пример #21
0
 def setUp(self):
     for error in Error.all():
         error.delete()
     for notification in Notification.all():
         notification.delete()
     for user in AppUser.all():
         user.delete()
     for issue in Issue.all():
         issue.delete()
Пример #22
0
    def setUp(self):
        u = SandstormUser(sid="xxxdummyxxx", name="Dummy User", handle="dummy")
        u.save()

        i1 = Issue(title="Foo", description="describe Foo", creator=u, deadline=date.today())
        i1.save()
        i2 = Issue(title="Bar", description="describe Bar", for_anon=True, creator=u, deadline=date.today() + timedelta(days=2))
        i2.save()
        i3 = Issue(title="Baz", description="describe Baz", subscriber_only=True, creator=u)
        i3.save()

        c1_1 = Comment(body="Hohoho", issue=i1, creator=u)
        c1_1.save()
        c2_1 = Comment(body="Funny!", issue=i1, creator=u)
        c2_1.save()
Пример #23
0
    def testIssueURL(self):
        self._setup()

        self.issue = Issue()
        self.issue.description = "This is a test"
        self.issue.project = self.project
        self.issue.save()

        assert self.issue.issueprojecturl_set.count() == 2
        assert self.issue.issueprojecturl_set[0].status == "not_fixed"
Пример #24
0
    def test_it_throws_an_exception_given_issue_already_exists(self) -> None:
        issue = Issue(
            number=1,
            name='any title',
            body='any body',
            main_language=ProgrammingLanguage.get_other_default_language(),
            repository=Repository.objects.create(
                name='iwannacontrib-issues-test-integration-test',
                owner=Owner.objects.create(owner='carlosmaniero')))
        issue.save()

        issues_url = "https://github.com/carlosmaniero/iwannacontrib-issues-test-integration-test/issues/1"
        issue_to_be_created = IssueToBeCreated(issues_url)
        service = CreateIssueService()

        with self.assertRaises(IssueAlreadyExists) as context:
            service.create_issue(self.github, issue_to_be_created)

        self.assertEquals(context.exception.url, issues_url)
Пример #25
0
    def testIssueAndErrorNotification(self):
        user = create_user()
        
        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        
        assert Issue.all().count() == 1

        c = Client()
        c.post(reverse("error-post"), test_data)

        #assert Notification.all().count() == 2
        # this would be 2 when issues are turned on
        assert Notification.all().count() == 1
        
        c = Client()
        res = c.get(reverse("notification-send"))        
        self.assertEquals(len(mail.outbox), 1)
Пример #26
0
    def create_issue(self, github: Github,
                     issue_to_be_created: IssueToBeCreated) -> Issue:
        github_issue = self._get_github_issue(github, issue_to_be_created)

        repository = Repository.objects.get_or_create(
            name=issue_to_be_created.repository,
            owner=Owner.objects.get_or_create(
                owner=issue_to_be_created.owner)[0])[0]

        if len(repository.issue_set.filter(
                number=issue_to_be_created.number)) != 0:
            raise IssueAlreadyExists(issue_to_be_created.url)

        issue = Issue(number=issue_to_be_created.number,
                      name=github_issue.title,
                      body=github_issue.body,
                      repository=repository,
                      main_language=self._get_main_language(github_issue))
        issue.save()
        return issue
Пример #27
0
    def add(self, language_name='Python', **rewrite):
        self.issue_number += 1

        data = dict(number=self.issue_number,
                    name=f'any title {self.issue_number}',
                    body='any body',
                    main_language=ProgrammingLanguage.objects.get_or_create(
                        name=language_name)[0],
                    repository=Repository.objects.get_or_create(
                        name='iwannacontrib-issues-test-integration-test',
                        owner=Owner.objects.get_or_create(
                            owner='carlosmaniero')[0])[0])

        data.update(**rewrite)

        issue = Issue(**data)

        issue.save()

        return issue
Пример #28
0
    def test_create_proposal(self):
        i = Issue(community=self.community, title="Issue ABC",
                  created_by=self.chairmen[0])
        i.full_clean()
        i.save()

        title = 'Proposal XYZ'
        content = 'hellow world'

        self.assertEquals(0, Proposal.objects.count())

        self.login_chairmen()
        url = reverse('proposal_create', args=(self.community.id, i.id))
        response = self.client.get(url)
        self.assertEquals(200, response.status_code)
        response = self.client.post(url, {
            'proposal-type': ProposalType.RULE,
            'proposal-title': title,
            'proposal-content': content,
            'proposal-tags': 'tag1,tag2,tag3',
        })
        self.assertEquals(200, response.status_code)
        # Ajax call returns a partial html
        self.assertEquals(1, Proposal.objects.count())
        p = Proposal.objects.all()[0]
        assert isinstance(p, Proposal)
        self.assertContains(response, p.get_absolute_url())
        self.assertEquals(title, p.title)
        self.assertEquals(content, p.content)
Пример #29
0
 def setUp(self):
     for issue in Issue.all():
         issue.delete()
     for log in Log.all():
         log.delete()
     for comment in Comment.all():
         comment.delete()
     for group in Group.all():
         group.delete()
     for error in Error.all():
         error.delete()
     for project in Project.all():
         project.delete()
Пример #30
0
    def testIssueNotification(self):
        user = create_user()

        issue = Issue()
        issue.description = "This is a test"
        issue.save()

        assert Issue.all().count() == 1
Пример #31
0
def resource_report(request,
                    object_id,
                    template_name='depot/resource_report.html'):
    """
    View for reporting a report when a user finds a problem with it.
    """
    resource = get_one_or_404(Resource, id=ObjectId(object_id))
    reporter = get_account(request.user.id)

    # if 'next' in request.GET:
    #     url = request.GET['next']
    # else:
    #     url = None
    # url = url or reverse('resource', args=[resource.id])

    if Issue.objects(reporter=reporter, related_document=resource).count():
        messages.warning(request, 'You have already reported this resource.')
        return HttpResponseRedirect(reverse('resource', args=[resource.id]))

    if request.method == 'POST':
        form = ResourceReportForm(request.POST)
        if form.is_valid():

            severity = int(form.cleaned_data['severity'])
            message = form.cleaned_data['message']

            issue = Issue(message=message,
                          severity=severity,
                          reporter=reporter)
            issue.related_document = resource
            issue.save()
            issue.notify_created()

            # only moderate as STATUS_BAD if SEVERITY_CRITICAL
            if severity == SEVERITY_CRITICAL:
                resource.moderate_as_bad(reporter)

            return HttpResponseRedirect(
                reverse('issue_detail', args=[issue.id]))
    else:
        form = ResourceReportForm()

    return render_to_response(
        template_name, {
            'next': urlquote_plus(request.GET.get('next', '')),
            'form': form,
            'object': resource,
        }, RequestContext(request))
    def handle(self,
               count,
               service,
               min_lat=None,
               max_lat=None,
               min_lon=None,
               max_lon=None,
               **options):
        service = Service.objects.get(service_code=service)
        for i in range(count):
            lat = long = None
            if min_lat and max_lat and min_lon and max_lon:
                lat = random.uniform(min_lat, max_lat)
                long = random.uniform(min_lon, max_lon)

            issue = Issue(
                service=service,
                lat=lat,
                long=long,
                submitter_email='*****@*****.**',
                description=generate_description(),
            )
            issue.save()
        self.stdout.write('{} issues created'.format(count))
Пример #33
0
def create_issue(request, issue_state):
	data=None
	if issue_state =='create':
		data={
			'issue_form': IssueForm(),
			'issue_create':'active',
			'page_title':'Create Issue',
			'system_name':'Create Issue',
		}
	elif issue_state =='save':
		if request.method == 'POST':
			iss_form = IssueForm(request.POST, request.FILES)
			
			if iss_form.is_valid():
					
				dt = datetime.datetime.now()
				curr=request.user

				if not Issue.objects.filter(title__iexact=iss_form.cleaned_data['title'] ).exists():

					issue_meta = Issue(
						issue_volume = 		int(iss_form.cleaned_data['issue_volume']),
						issue_number = 		int(iss_form.cleaned_data['issue_number']),
						issue_year = 		iss_form.cleaned_data['issue_year'],
						title = 			iss_form.cleaned_data['title'],
						description = 		iss_form.cleaned_data['description'],
						printIssn =			iss_form.cleaned_data['printIssn'],
						is_published =		False,
						# special_issue =     models.BooleanField(default = False)
					)
					issue_meta.save()

					if 'cover_photo' in request.FILES:
						# print(request.FILES['image_path'])
						issue_meta.cover_photo = request.FILES['cover_photo']

					issue_meta.save()

					request.session['issue_saved'] = issue_meta.id
				else:
					request.session['issue_saved'] = 0
				return HttpResponseRedirect('/joumsy/issues_view/not_published')
			
		else:
			print('not post')
				
	# json_response = json.dumps(data)
	# return HttpResponse(json_response, content_type="application/json")
	return render(request,'journals/index_issue.html', data)
Пример #34
0
def edit_project_url(request, pk):
    issue = Issue.get(pk)
    urls = IssueProjectURL.all().filter("issue = ", issue)
    url_ids = dict([ (url.id, url) for url in urls ])
    if request.POST:
        for key, value in request.POST.items():
            if key in url_ids:
                assert value in [ i[0] for i in issue_project_url_statuses ], \
                    "%s not in %s" % (value, issue_project_url_statuses)
                url_ids[key].status = value
                url_ids[key].save()
        return HttpResponseRedirect(reverse("issues-view", args=[pk,]))
    return direct_to_template(request, "issue_project_url.html", extra_context={
        "issue": issue,
        "urls": urls,
        "issue_project_url_statuses": issue_project_url_statuses,
        "nav": {"selected": "issues",},
    })
Пример #35
0
def resource_report(request, object_id, template_name='depot/resource_report.html'):
    """
    View for reporting a report when a user finds a problem with it.
    """
    resource = get_one_or_404(Resource, id=ObjectId(object_id))
    reporter=get_account(request.user.id)

    # if 'next' in request.GET:
    #     url = request.GET['next']
    # else:
    #     url = None
    # url = url or reverse('resource', args=[resource.id])

    if Issue.objects(reporter=reporter, related_document=resource).count():
        messages.warning(request, 'You have already reported this resource.')
        return HttpResponseRedirect(reverse('resource', args=[resource.id]))

    if request.method == 'POST':
        form = ResourceReportForm(request.POST)
        if form.is_valid():

            severity=int(form.cleaned_data['severity'])
            message=form.cleaned_data['message']

            issue = Issue(
                message=message,
                severity=severity,
                reporter=reporter)
            issue.related_document = resource
            issue.save()
            issue.notify_created()
            
            # only moderate as STATUS_BAD if SEVERITY_CRITICAL
            if severity == SEVERITY_CRITICAL:
                resource.moderate_as_bad(reporter)

            return HttpResponseRedirect(reverse('issue_detail', args=[issue.id]))
    else:
        form = ResourceReportForm()

    return render_to_response(template_name, {
        'next': urlquote_plus(request.GET.get('next', '')),
        'form': form,
        'object': resource,
    }, RequestContext(request))
Пример #36
0
def index(request, show=None):
    issues = None
    if show:
        kind_filter = index_filters.get(show, None)
        if kind_filter is None:
            return HttpResponseNotFound()
        issues = Issue.filter_by_kinds(kind_filter).filter(public=True).all()
    else:
        return render_to_response('issues/welcome.html', context_instance=RequestContext(request))

    issues = map(Issue.get_typed, issues)
    random.shuffle(issues)

    if show == 'grad':
        newissues = list()
        for i in issues:
            if i.kind == oe_constants.ISSUE_SPECFEE and i.is_grad_issue() == False:
                continue
            newissues.append(i)
        issues = newissues

    return render_to_response('issues/index.html', {'issues': issues, 'detail': False}, context_instance=RequestContext(request))
Пример #37
0
    def testIssueAndErrorNotification(self):
        user = create_user()

        issue = Issue()
        issue.description = "This is a test"
        issue.save()

        assert Issue.all().count() == 1

        c = Client()
        c.post(reverse("error-post"), test_data)

        #assert Notification.all().count() == 2
        # this would be 2 when issues are turned on
        assert Notification.all().count() == 1

        c = Client()
        res = c.get(reverse("notification-send"))
        self.assertEquals(len(mail.outbox), 1)
Пример #38
0
 def test_vote_proposal(self):
     #        p = self.test_create_proposal()
     ######################################
     i = Issue(community=self.community,
               title="Issue ABC",
               created_by=self.chairmen[0])
     i.full_clean()
     i.save()
     title = 'Proposal XYZ'
     content = 'hellow world'
     p = Proposal.objects.create(type=ProposalType.RULE,
                                 issue=i,
                                 created_by=self.chairmen[0],
                                 title=title,
                                 content=content)
     ######################################
     #TODO: create this via HTML request
     pv = ProposalVote(proposal=p,
                       user=self.members[0],
                       value=ProposalVoteValue.CON)
     pv.full_clean()
     pv.save()
     return pv
Пример #39
0
    def test_issue_create_filled(self):
        year = Year.objects.create(start_year=2016)
        group = Group.objects.create(name='name_groups', year=year)
        course = Course.objects.create(name='course_name',
                                       year=year)
        course.groups = [group]
        course.save()
        task = Task.objects.create(title='task',
                                   course=course)
        student = User.objects.create_user(username='******',
                                           password='******')
        responsible = User.objects.create_user(username='******',
                                               password='******')
        followers = [User.objects.create_user(username='******',
                                              password='******')]

        status = IssueStatus.objects.get(name=u'{"ru": "Зачтено", "en": "Accepted"}')

        issue = Issue()
        issue.student = student
        issue.task = task
        issue.mark = 3
        issue.responsible = responsible
        issue.status_field = status
        issue.save()
        issue.followers = followers
        issue.save()
        issue_id = issue.id

        issue = Issue.objects.get(id=issue_id)

        self.assertIsInstance(issue, Issue)
        self.assertEqual(issue.student, student)
        self.assertEqual(issue.task, task)
        self.assertEqual(issue.mark, 3)
        self.assertEqual(issue.responsible, responsible)
        self.assertEqual(issue.status_field, status)
        self.assertItemsEqual(issue.followers.all(), followers)
Пример #40
0
class Github(TrackerPlugin):

    id = 'github'
    name = 'Github issue synchronisation'
    api_url = 'http://github.com/api/v2/json/issues'

    def _make_request(self, url):
        req = urllib2.Request(url)
        fo = urllib2.urlopen(req)
        response = fo.read()
        response = simplejson.loads(response)
        fo.close()
        return response

    def _update_user_data(self, config, data, issue):
        names = [data.get('user')]
        url = '%(base_url)s/comments/%(user)s/%(project)s/%(issue)s' % {
            'base_url': self.api_url,
            'user': config.get('user'),
            'project': config.get('project'),
            'issue': issue.no}
        response = self._make_request(url)
        for comment in response.get('comments', []):
            names.append(comment.get('user'))
        names = list(set(names))
        self.update_user_mapping(issue, names)

    def sync(self, tracker):
        m = CONFIG_PATTERN.match(tracker.config)
        if not m:
            raise StandardError('Invalid configuration information.'
                                ' Please use a format like user@project.')
        config = m.groupdict()
        response = {}
        url = '%(base_url)s/list/%(user)s/%(project)s/%%s' % {
            'base_url': self.api_url,
            'user': config.get('user'),
            'project': config.get('project')}
        try:
            response_closed = self._make_request(url % 'closed')
            response_open = self._make_request(url % 'open')
        except urllib2.HTTPError, e:
            self._log.error(str(e))
            return False
        issues = response_closed.get('issues', [])
        issues.extend(response_open.get('issues'))
        for data in issues:
            tid = data.get('number')
            created = _github_date_to_datetime(data.get('created_at'))
            updated = _github_date_to_datetime(data.get('updated_at'))
            if (created >= tracker.last_update
                or updated >= tracker.last_update):
                issue = Issue.by_tracker_id(tracker.id, tid)
                issue.no = tid
                issue.set_title(data.get('title', ''))
                issue.set_description(data.get('body', ''))
                issue.tracker = tracker
                issue.last_change = updated
                issue.owner = data.get('user')
                issue.reporter = data.get('user')
                if data.get('closed_at', None):
                    issue.active = False
                else:
                    issue.active = True
                if not issue.id:
                    issue.created = datetime.now()
                issue.updated = datetime.now()
                issue.save()
                post_issue_sync.send(sender=self, issue=issue)
                # Currently disabled due to API call limitations
                #self._update_user_data(config, data, issue)
            else:
                continue
        tracker.last_update = datetime.now() - timedelta(days=1)
        tracker.save()
        post_tracker_sync.send(sender=self, tracker=tracker)
        return True
Пример #41
0
def create(request):
    errors = []

    if 'submit' in request.POST:
        issue = Issue()
        issue.title = request.POST['title']
        issue.content = request.POST['content']
        issue.creator = request.user

        due_time = request.POST.get('due_time', '').strip()
        if len(due_time):
            try:
                due_time = parse_date(due_time)
                if due_time:
                    issue.due_time = due_time
                else:
                    errors.append('date-misformed')
            except ValueError:
                errors.append('date-invalid')

        assignee = request.POST.get('assignee')
        if assignee:    # Empty value => not assigned, no need to set
            try:
                issue.assignee = User.objects.get(id=assignee)
            except User.DoesNotExist:
                assignee = None        # Just in case we're under attack...

        labels = []
        for label_id in request.POST.getlist('labels'):
            try:
                labels.append(Label.objects.get(id=label_id))
            except Label.DoesNotExist: pass

        if not errors:
            issue.save()    # Need to save before we can enforce N to N relationship
            issue.starring.add(request.user)    # Auto watch

            # Add or remove labels has history so we don't worry on history creation
            issue.labels.add(*labels)

            mentions, _ = filter_mentions(issue.content)
            if assignee:
                mentions.add(issue.assignee)
            mentions.discard(request.user)

            for user in mentions:
                issue.starring.add(user)    # Auto watch
                send_mail(request.user, user, 'mail/issue_created.html', { 'issue': issue })

            # Broadcast new issues automatically
            send_mail(request.user, settings.BROADCAST_EMAIL, 'mail/issue_created.html', { 'issue': issue })

            if assignee:
                IssueHistory.objects.create(issue=issue, user=request.user,
                                            mode=IssueHistory.ASSIGN, content=assignee)

            if due_time:
                IssueHistory.objects.create(issue=issue, user=request.user,
                                            mode=IssueHistory.SET_DUE, content=due_time)

            return redirect('issues:detail', issue.id)

    return render(request, 'issues/create.html', {
        'labels': Label.objects.all(),
        'users': sorted_users(User.objects.filter(is_active=True)),
        'errors': errors,
    })
         err.errcode, err.errmsg))
     return False
 except Error, err:
     self._log.error('Error: %s' % err)
     return False
 except:
     self._log.error('Unknown error: %s' % str(sys.exc_info()[1]))
     return False
 self._log.info('Trac XMLRPC-API version: %s' % '.'.join(map(
     str, api_version)))
 d = DateTime(time.mktime(tracker.last_update.timetuple()))
 self._log.info('Last update: %s' % d)
 tids = server.ticket.getRecentChanges(d)
 self._log.info('Issue updates: %s' % `tids`)
 for tid in tids:
     issue = Issue.by_tracker_id(tracker.id, tid)
     id_, cr_date, last_change, data = server.ticket.get(tid)
     #if isinstance(cr_date, int):
         #cr_date = datetime.fromtimestamp(cr_date)
         #last_change = datetime.fromtimestamp(last_change)
     issue.no = id_
     issue.set_title(data.get('summary', ''))
     issue.set_description(data.get('description', ''))
     issue.reporter = data.get('reporter')
     issue.owner = data.get('owner')
     issue.last_change = last_change
     issue.tracker = tracker
     # Only default status values are allowed as Trac allows renaming
     # of status values.
     resolution = data.get('resolution')
     issue.active = resolution in ACTIVE_STATUS
Пример #43
0
 def _issue(self):
     self.issue = Issue()
     self.issue.description = "This is a test"
     self.issue.save()
Пример #44
0
 def _issue(self):
     self.issue = Issue()
     self.issue.description = "This is a test"
     self.issue.save()
Пример #45
0
    def testLogAdded(self):
        issue = Issue()
        issue.description = "This is a test"
        issue.save()

        assert issue.log_set[0]
Пример #46
0
class ErrorTests(TestCase):
    # test the view for writing errors
    def setUp(self):
        for issue in Issue.all(): issue.delete()
        for log in Log.all(): log.delete()
        for comment in Comment.all(): comment.delete()
        for group in Group.all(): group.delete()
        for error in Error.all(): error.delete()
        for project in Project.all(): project.delete()

    def testLogAdded(self):
        issue = Issue()
        issue.description = "This is a test"
        issue.save()

        assert issue.log_set[0]

    def _setup(self):
        self.project = Project(name="testing")
        self.project.save()

        self.url = ProjectURL(url="http://test.areciboapp.com")
        self.url.project = self.project
        self.url.save()

        self.url = ProjectURL(url="http://www.areciboapp.com")
        self.url.project = self.project
        self.url.save()

        self.error = Error()
        for k, v in break_url("http://test.areciboapp.com/an/other").items():
            setattr(self.error, k, v)
        self.error.save()

    def _issue(self):
        self.issue = Issue()
        self.issue.description = "This is a test"
        self.issue.save()

    def testIssueGroup(self):
        self._setup()

        self._issue()

        group = Group.all()[0]
        self.issue.add_group(group)

        assert group == self.issue.issuegroup_set[0].group
        assert self.issue.issuegroup_set.count() == 1

        assert self.issue == IssueGroup.all().filter("issue = ", self.issue)[0].issue

    def testIssueURL(self):
        self._setup()

        self.issue = Issue()
        self.issue.description = "This is a test"
        self.issue.project = self.project
        self.issue.save()

        assert self.issue.issueprojecturl_set.count() == 2
        assert self.issue.issueprojecturl_set[0].status == "not_fixed"

    def testIssueURLFlexibility(self):
        self._setup()

        self._issue()
        assert self.issue == issue_by_number(self.issue.number)
        assert self.issue == issue_by_number(self.issue.number)

    def testIssueChanged(self):
        self.signal_fired = False
        def signal_fired(instance, old, **kw):
            self.signal_fired = True
        signals.issue_changed.connect(signal_fired, dispatch_uid="issue_changed")
        self._issue()
        self.issue.status = "rejected"
        self.issue.save()
        assert self.signal_fired

    def testIssuePriorityChanged(self):
        self.signal_fired = False
        def signal_fired(instance, old, new, **kw):
            self.signal_fired = True
            assert old in (None, 1)
            assert new in (1, 2)

        signals.issue_priority_changed.connect(signal_fired, dispatch_uid="issue_priority_changed")

        self._issue()
        self.issue.priority = 1
        self.issue.save()
        assert self.signal_fired

        self.signal_fired = False
        self.issue.priority = 2
        self.issue.save()
        assert self.signal_fired

    def testIssueStatusChanged(self):
        self.signal_fired = False
        def signal_fired(instance, old, new, **kw):
            self.signal_fired = True
            assert not old
            assert new == "rejected"

        signals.issue_status_changed.connect(signal_fired, dispatch_uid="issue_status_changed")

        self._issue()
        self.issue.status = "rejected"
        self.issue.save()
        assert self.signal_fired

        self.signal_fired = False
        self.issue.priority = 1
        self.issue.save()
        assert not self.signal_fired
Пример #47
0
def create(request):
    if request.method == 'POST':
        try:
            name = request.POST['name']
            description = request.POST['description']
            lat = request.POST['latitude']
            lng = request.POST['longitude']

        except:
            raise Http404

        issue = Issue()
        issue.name = name
        issue.description = description

        logging.debug('Debug latitude')

        issue.latitude = lat
        issue.longitude= lng

        issue.save()
        try:
            logging.debug('Saving issue')
            issue.save()

            # send email
            issue.new_issue_email()
        except:
            raise Http404

        return render(request, 'issues/show.html', {'issue': issue})
Пример #48
0
def issue_status(resource):
    result = -1
    for issue in Issue.objects(related_document=resource, resolved=0):
        result = issue.severity if issue.severity > result else result
    return result
Пример #49
0
def manage_index(request):
    sunetid = request.user.webauth_username
    issues = map(Issue.get_typed, Issue.filter_by_sponsor(sunetid))
    return render_to_response('issues/manage/index.html', {'issues': issues}, context_instance=RequestContext(request))
Пример #50
0
from sys import argv
import django
django.setup()

saveToDatabase=argv[1]

from django.utils import timezone
from issues.models import Issue, Assignee

issue = Issue(issue_label="test issue", pub_date=timezone.now())
if saveToDatabase == "save":
  issue.save()
  print "Issue id: %i" % issue.id
print issue

assignee = Assignee(name="John Hakala", email="*****@*****.**")
if saveToDatabase == "save":
  assignee.save()
  print "Assignee id: %i"  % assignee.id
print assignee
Пример #51
0
    def testIssueNumber(self):
        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 1

        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 2

        old_issue = issue

        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 3, issue.number

        old_issue.delete()

        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 4
Пример #52
0
	else:
		usr = Author()
		usr_dict[user_id] = usr

	if (obj['meta_key'] == 'first_name'):
		usr.first_name = obj['meta_value']
		print usr

	if (obj['meta_key'] == 'last_name'):
		usr.last_name = obj['meta_value']

for k, v in usr_dict.items():
	v.save()


oldissue = Issue(volume = 109, issue = 1)
oldissue.save()

post_data=open('posteroo.json')

data = json.load(post_data)

post_dict = {}

for obj in data:
	if (obj['post_status'] != "publish"):
		continue;

	if (len(obj['post_content']) == 0) :
		continue;
Пример #53
0
    def testLogAdded(self):
        issue = Issue()
        issue.description = "This is a test"
        issue.save()

        assert issue.log_set[0]
Пример #54
0
    def testIssueNumber(self):
        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 1

        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 2

        old_issue = issue

        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 3, issue.number

        old_issue.delete()

        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 4
Пример #55
0
class ErrorTests(TestCase):
    # test the view for writing errors
    def setUp(self):
        for issue in Issue.all():
            issue.delete()
        for log in Log.all():
            log.delete()
        for comment in Comment.all():
            comment.delete()
        for group in Group.all():
            group.delete()
        for error in Error.all():
            error.delete()
        for project in Project.all():
            project.delete()

    def testLogAdded(self):
        issue = Issue()
        issue.description = "This is a test"
        issue.save()

        assert issue.log_set[0]

    def testIssueNumber(self):
        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 1

        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 2

        old_issue = issue

        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 3, issue.number

        old_issue.delete()

        issue = Issue()
        issue.description = "This is a test"
        issue.save()
        assert issue.number == 4

    def _setup(self):
        self.project = Project(name="testing")
        self.project.save()

        self.url = ProjectURL(url="http://test.areciboapp.com")
        self.url.project = self.project
        self.url.save()

        self.url = ProjectURL(url="http://www.areciboapp.com")
        self.url.project = self.project
        self.url.save()

        self.error = Error()
        for k, v in break_url("http://test.areciboapp.com/an/other").items():
            setattr(self.error, k, v)
        self.error.save()

    def _issue(self):
        self.issue = Issue()
        self.issue.description = "This is a test"
        self.issue.save()

    def testIssueGroup(self):
        self._setup()

        self._issue()

        group = Group.all()[0]
        self.issue.add_group(group)

        assert group == self.issue.issuegroup_set[0].group
        assert self.issue.issuegroup_set.count() == 1

        assert self.issue == IssueGroup.all().filter("issue = ",
                                                     self.issue)[0].issue

    def testIssueURL(self):
        self._setup()

        self.issue = Issue()
        self.issue.description = "This is a test"
        self.issue.project = self.project
        self.issue.save()

        assert self.issue.issueprojecturl_set.count() == 2
        assert self.issue.issueprojecturl_set[0].status == "not_fixed"

    def testIssueURLFlexibility(self):
        self._setup()

        self._issue()
        assert self.issue == issue_by_number(self.issue.number)
        assert self.issue == issue_by_number(self.issue.number)

    def testIssueChanged(self):
        self.signal_fired = False

        def signal_fired(instance, old, **kw):
            self.signal_fired = True

        signals.issue_changed.connect(signal_fired,
                                      dispatch_uid="issue_changed")
        self._issue()
        self.issue.status = "rejected"
        self.issue.save()
        assert self.signal_fired

    def testIssuePriorityChanged(self):
        self.signal_fired = False

        def signal_fired(instance, old, new, **kw):
            self.signal_fired = True
            assert old in (None, 1)
            assert new in (1, 2)

        signals.issue_priority_changed.connect(
            signal_fired, dispatch_uid="issue_priority_changed")

        self._issue()
        self.issue.priority = 1
        self.issue.save()
        assert self.signal_fired

        self.signal_fired = False
        self.issue.priority = 2
        self.issue.save()
        assert self.signal_fired

    def testIssueStatusChanged(self):
        self.signal_fired = False

        def signal_fired(instance, old, new, **kw):
            self.signal_fired = True
            assert not old
            assert new == "rejected"

        signals.issue_status_changed.connect(
            signal_fired, dispatch_uid="issue_status_changed")

        self._issue()
        self.issue.status = "rejected"
        self.issue.save()
        assert self.signal_fired

        self.signal_fired = False
        self.issue.priority = 1
        self.issue.save()
        assert not self.signal_fired
Пример #56
0
class AnyContestTest(TestCase):
    @classmethod
    def setUpClass(cls):
        cls.contest = ContestServerMock()
        cls.contest.start()
        time.sleep(0.5)

        cls.contest_port = cls.contest.httpd.server_address[1]

    @classmethod
    def tearDownClass(cls):
        cls.contest.stop()

    def setUp(self):
        self.year = Year.objects.create(start_year=2016)
        self.group = Group.objects.create(name='name_groups', year=self.year)
        self.course = Course.objects.create(name='course_name', year=self.year)
        self.course.groups = [self.group]
        self.course.save()

        self.task = Task.objects.create(title='task',
                                        course=self.course,
                                        problem_id="A")
        self.student = User.objects.create_user(username='******',
                                                password='******')
        self.responsible = User.objects.create_user(username='******',
                                                    password='******')

        status = IssueStatus.objects.get(tag=Issue.STATUS_ACCEPTED)

        self.issue = Issue()
        self.issue.student = self.student
        self.issue.task = self.task
        self.issue.responsible = self.responsible
        self.issue.status_field = status
        self.issue.save()
        self.issue.save()
        self.issue_id = self.issue.id

    def test_contest_info(self):
        self.maxDiff = None
        # with override_settings(CONTEST_API_URL='http://127.0.0.1:{}/anytask/'.format(self.contest_port))
        self.assertDictEqual(
            get_contest_info(1, lang='ru')[1],
            tests_data.CONTEST_INFO['result'])

    def test_contest_submition_ok(self):
        contest_submition = ContestSubmission()
        contest_submition.issue = self.issue
        contest_submition.author = self.student

        event_create_file = Event.objects.create(
            issue=self.issue, field=IssueField.objects.get(name='file'))
        f = File.objects.create(file=SimpleUploadedFile(
            'test_rb.py', b'print "hello world!"'),
                                event=event_create_file)
        contest_submition.file = f

        contest_submition.save()

        self.assertTrue(contest_submition.upload_contest("py"))
        self.assertEquals(contest_submition.run_id, "1")

    def test_contest_submition_fail(self):
        contest_submition = ContestSubmission()
        contest_submition.issue = self.issue
        contest_submition.author = self.student

        event_create_file = Event.objects.create(
            issue=self.issue, field=IssueField.objects.get(name='file'))
        f = File.objects.create(file=SimpleUploadedFile(
            'test_fail_rb.py', b'print "_failed_"'),
                                event=event_create_file)
        contest_submition.file = f

        contest_submition.save()

        self.assertFalse(contest_submition.upload_contest("py"))
        self.assertEquals(contest_submition.send_error,
                          "Submit error in fake server!")

    def test_check_submission_ok(self):
        contest_submition = ContestSubmission()
        contest_submition.issue = self.issue
        contest_submition.author = self.student
        contest_submition.run_id = "1"

        event_create_file = Event.objects.create(
            issue=self.issue, field=IssueField.objects.get(name='file'))
        f = File.objects.create(file=SimpleUploadedFile(
            'test_fail_rb.py', b'print "_failed_"'),
                                event=event_create_file)
        contest_submition.file = f

        contest_submition.save()

        comment = contest_submition.check_submission()
        self.assertIn(u'<p>{0}: ok</p>'.format(_(u'verdikt_jakontest')),
                      comment)
        self.assertTrue(contest_submition.got_verdict)

    def test_check_submission_precompile_check_failed(self):
        contest_submition = ContestSubmission()
        contest_submition.issue = self.issue
        contest_submition.author = self.student
        contest_submition.run_id = "2"

        event_create_file = Event.objects.create(
            issue=self.issue, field=IssueField.objects.get(name='file'))
        f = File.objects.create(file=SimpleUploadedFile(
            'test_fail_rb.py', b'print "_failed_"'),
                                event=event_create_file)
        contest_submition.file = f

        contest_submition.save()

        comment = contest_submition.check_submission()
        self.assertIn(
            u'<p>{0}: precompile-check-failed</p>'.format(
                _(u'verdikt_jakontest')), comment)
        self.assertTrue(contest_submition.got_verdict)
        self.assertIn('precompile-check-failed-1', comment)
        self.assertIn('precompile-check-failed-2', comment)
        self.assertIn('precompile-check-failed-3', comment)

    def test_check_submission_failed(self):
        contest_submition = ContestSubmission()
        contest_submition.issue = self.issue
        contest_submition.author = self.student
        contest_submition.run_id = "3"

        event_create_file = Event.objects.create(
            issue=self.issue, field=IssueField.objects.get(name='file'))
        f = File.objects.create(file=SimpleUploadedFile(
            'test_fail_rb.py', b'print "_failed_"'),
                                event=event_create_file)
        contest_submition.file = f

        contest_submition.save()

        comment = contest_submition.check_submission()
        self.assertTrue(contest_submition.got_verdict)
        self.assertIn(u'<p>{0}: failed</p>'.format(_(u'verdikt_jakontest')),
                      comment)
        self.assertIn("1ms/1.91Mb", comment)
        self.assertIn("input", comment)
        self.assertIn("output", comment)
        self.assertIn("answer", comment)
        self.assertIn("error", comment)
        self.assertIn("message", comment)

    @skip("Bad error handling on this case")
    def test_check_submission_bad_answer(self):
        contest_submition = ContestSubmission()
        contest_submition.issue = self.issue
        contest_submition.author = self.student
        contest_submition.run_id = "4"

        event_create_file = Event.objects.create(
            issue=self.issue, field=IssueField.objects.get(name='file'))
        f = File.objects.create(file=SimpleUploadedFile(
            'test_fail_rb.py', b'print "_failed_"'),
                                event=event_create_file)
        contest_submition.file = f

        contest_submition.save()

        contest_submition.check_submission(
        )  # Contest returns 501 here and no JSON
        self.assertFalse(contest_submition.got_verdict)

    def test_check_submission_wrong_json(self):
        contest_submition = ContestSubmission()
        contest_submition.issue = self.issue
        contest_submition.author = self.student
        contest_submition.run_id = "5"

        event_create_file = Event.objects.create(
            issue=self.issue, field=IssueField.objects.get(name='file'))
        f = File.objects.create(file=SimpleUploadedFile(
            'test_fail_rb.py', b'print "_failed_"'),
                                event=event_create_file)
        contest_submition.file = f

        contest_submition.save()

        contest_submition.check_submission()
        self.assertFalse(contest_submition.got_verdict)
Пример #57
0
    def _submit_review(self, request, task, svn_path):
        user = request.user

        try:
            rev_a = int(request.POST.get('rev_a'))
            rev_b = int(request.POST.get('rev_b'))
        except TypeError: #not int
            return HttpResponseForbidden()
        except ValueError: #not int
            return HttpResponseForbidden()

        if rev_a == rev_b:
            return HttpResponseForbidden()

        if rev_b < rev_a:
            rev_a, rev_b = rev_b, rev_a

        review_id = None
        try:
            issue = Issue.objects.filter(task=task, student=user).order_by('-update_time')[0]
            review_id = issue.rb_review_id
        except Issue.DoesNotExist:
            pass
        except IndexError:
            pass

        issue = Issue()
        issue.task = task
        issue.student = user
        issue.svn_commit_id = rev_b

        summary = u"[{0}][{1}] {2}".format(user.get_full_name(), task.course.get_user_group(user), task.title)

        review_group_name = settings.RB_API_DEFAULT_REVIEW_GROUP
        if task.course.name_id:
            review_group_name =  "teachers_{0}".format(task.course.name_id)
        else:
            try:
                review_group_name = "teachers_{0}".format(task.course.name)
            except Exception:
                pass

        review_group_name = review_group_name.replace(".", "_")
        review_group_name = review_group_name.replace("/", "_")
        review_group_name = review_group_name.lower()

        anyrb = AnyRB()

        description = self._get_description(request, task, svn_path, rev_a, rev_b)
        if review_id is None:
            review_id = anyrb.submit_review(user, rev_a, rev_b, summary=summary, description=description, review_group_name=", ".join((review_group_name, settings.RB_API_DEFAULT_REVIEW_GROUP)),  path=svn_path)
        else:
            anyrb.update_review(user, rev_a, rev_b, review_id, description=description, path=svn_path)

        issue.rb_review_id = review_id
        issue.save()

        context = {
            'review_url' : anyrb.get_review_url(request, review_id),
            'task' : task,
        }

        return render_to_response('submit_review_done.html', context, context_instance=RequestContext(request))
Пример #58
0
def create(request):
    errors = []

    if 'submit' in request.POST:
        issue = Issue()
        issue.title = request.POST['title']
        issue.content = request.POST['content']
        issue.creator = request.user

        due_time = request.POST.get('due_time', '').strip()
        if len(due_time):
            try:
                due_time = parse_date(due_time)
                if due_time:
                    issue.due_time = due_time
                else:
                    errors.append('date-misformed')
            except ValueError:
                errors.append('date-invalid')

        assignee = request.POST.get('assignee')
        if assignee:  # Empty value => not assigned, no need to set
            try:
                issue.assignee = User.objects.get(id=assignee)
            except User.DoesNotExist:
                assignee = None  # Just in case we're under attack...

        labels = []
        for label_id in request.POST.getlist('labels'):
            try:
                labels.append(Label.objects.get(id=label_id))
            except Label.DoesNotExist:
                pass

        if not errors:
            issue.save(
            )  # Need to save before we can enforce N to N relationship
            issue.starring.add(request.user)  # Auto watch

            # Add or remove labels has history so we don't worry on history creation
            issue.labels.add(*labels)

            mentions, _ = filter_mentions(issue.content)
            if assignee:
                mentions.add(issue.assignee)
            mentions.discard(request.user)

            for user in mentions:
                issue.starring.add(user)  # Auto watch
                send_mail(request.user, user, 'mail/issue_created.html',
                          {'issue': issue})

            # Broadcast new issues automatically
            send_mail(request.user, settings.BROADCAST_EMAIL,
                      'mail/issue_created.html', {'issue': issue})

            if assignee:
                IssueHistory.objects.create(issue=issue,
                                            user=request.user,
                                            mode=IssueHistory.ASSIGN,
                                            content=assignee)

            if due_time:
                IssueHistory.objects.create(issue=issue,
                                            user=request.user,
                                            mode=IssueHistory.SET_DUE,
                                            content=due_time)

            return redirect('issues:detail', issue.id)

    return render(
        request, 'issues/create.html', {
            'labels': Label.objects.all(),
            'users': sorted_users(User.objects.filter(is_active=True)),
            'errors': errors,
        })
Пример #59
0
class TestViews(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user('testuser', '*****@*****.**',
                                             'testpassword')
        self.client.login(username='******', password='******')
        self.open_bug = Issue(issue_type='bug',
                              title='testbug1',
                              description='testdescription1',
                              author=self.user)
        self.open_bug.save()
        self.open_feature = Issue(issue_type='feature',
                                  title='testfeature1',
                                  description='testdescription1',
                                  author=self.user)
        self.open_feature.save()
        self.closed_bug = Issue(issue_type='bug',
                                title='testbug2',
                                description='testdescription2',
                                author=self.user,
                                status='closed')
        self.closed_bug.save()
        self.closed_bug.date_complete = timezone.now()
        self.closed_bug.save()
        self.closed_feature = Issue(issue_type='feature',
                                    title='testfeature2',
                                    description='testdescription2',
                                    author=self.user,
                                    status='closed')
        self.closed_feature.save()
        self.closed_feature.date_complete = timezone.now()
        self.closed_feature.save()

    def test_get_stats_page(self):
        cart_item = Cart(title='new suggested feature',
                         description='will make the app better',
                         user=self.user,
                         request_type='new feature',
                         amount=50)
        cart_item.save()
        response = self.client.get(reverse(stats))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'stats.html')

    def test_top_bugs(self):
        response = self.client.get(reverse(top_bugs))
        self.assertEqual(response.status_code, 200)

    def test_top_features(self):
        response = self.client.get(reverse(top_features))
        self.assertEqual(response.status_code, 200)

    def test_bug_closure(self):
        response = self.client.get(reverse(bug_closure))
        self.assertEqual(response.status_code, 200)

    def test_feature_closure(self):
        response = self.client.get(reverse(feature_closure))
        self.assertEqual(response.status_code, 200)