def test_renumber_ballot(self): proj = Project(name='test', order=0, doc_type='STD', description='test_renumber_ballot', task_group='TGx', par_date=datetime.datetime.now()) proj.save() self.failUnlessEqual(Project.objects.count(), 1) self.failUnlessEqual(Ballot.objects.count(), 0) bal = Ballot(number=123, project=proj, draft='1.0', opened=datetime.datetime.now(), pool=100) bal.closed = bal.opened + datetime.timedelta(days=15) bal.save() self.failUnlessEqual(Ballot.objects.count(), 1) url = reverse('ballot.views.main_page', args=[]) self._check_page(url) #response = self.client.get(url) self.wait_for_backlog_completion(DenormalizedBallot, 10) dn = DenormalizedBallot.objects.get(pk=bal.pk) bal2 = Ballot.objects.get(number=bal.number) bal2.number = 321 bal2.save() Ballot.objects.get(number=123).delete() self.wait_for_backlog_completion(DenormalizedBallot, 10) self.failUnlessRaises(DenormalizedBallot.DoesNotExist, DenormalizedBallot.objects.get, number=123) dn = DenormalizedBallot.objects.get(number=bal2.number)
def create(data, user): createDate = datetime.now().strftime('%Y%m%d') projectsToday = Project.objects.filter(createDate=createDate).order_by('-id') nextIndex = "%02d" % (1 + int(projectsToday[0].dateIndex) if projectsToday.count() else 1) parent = Project.objects.get(id=data['parent']) if data['parent'] != '0' else None project = Project(status=1, name=data['name'], type=data['type'], department=data['department'],suffix=data['suffix'],remote=data['allRemote'], relatedId=data['relatedId'], onlineDate=data['onlineDate'], testType=1, createDate=createDate, dateIndex=nextIndex, createPerson=user.pk, parent=parent, pmtType=data['pmtType'],delay=0) # 新建项目 project.save() projectExtend = ProjectExtend(project=project, description=data['description']) projectExtend.save() try: staffs = Pmt().getRelativeStaffsByProjectId(project.relatedId)['task'] or [] print ("---------------") print (staffs) # if len(staffs) > 0: for staff in staffs: position=staff['position'] if '质量' in position: position='QA' staffModel = RelatedPerson(project=project, relatedId=1, \ name=staff['english_name'], chineseName=staff['chinese_name'], \ email=staff['email'], position=position, type=0) staffModel.save() except: print("==========") return project.id
def setUpTestData(cls): # NOTE: if you modify those elements they need to be created in setUp, instead of here cls.user = get_user_model().objects.create_user('a', 'b', 'c') cls.user2 = get_user_model().objects.create_user('d', 'e', 'f') cls.project = Project(creator=cls.user, name_short='PRJ') cls.project.save() cls.project.developer.add(cls.user) cls.project2 = Project(creator=cls.user, name_short='PROJ') cls.project2.save() cls.project2.developer.add(cls.user) cls.project2.developer.add(cls.user2) # create test data (They are needed for search-purpose only) cls.issue = Issue(title="Test-Issue", project=cls.project, kanbancol=cls.project.kanbancol.first(), type="Bug") cls.issue.save() issue = Issue(title="Blub-Issue", project=cls.project, kanbancol=cls.project.kanbancol.first(), type="Bug") issue.save() issue = Issue(title="Bla-Issue", project=cls.project, kanbancol=cls.project.kanbancol.first(), type="Task") issue.save() cls.issuep2 = Issue(title="Bling-Issue", project=cls.project2, kanbancol=cls.project2.kanbancol.first(), type="Task") cls.issuep2.due_date = datetime.date(2000, 1, 1) cls.issuep2.save()
def add_project_save(request): if request.method != "POST": messages.error(request, "Invalid Method!") return redirect('add_project') else: form = AddFileForm(request.POST, request.FILES) if form.is_valid(): p_id = form.cleaned_data['p_id'] title = form.cleaned_data['title'] description = form.cleaned_data['description'] status = form.cleaned_data['status'] if(len(request.FILES) != 0): report = request.FILES['report'] fs = FileSystemStorage() filename = fs.save(report.name,report) report_url = fs.url(filename) else: report_url = None try: project = Project(p_id = p_id, title = title, description = description, status = status, report = report_url) project.save() messages.success(request, "Project Added Successfully!") return redirect('add_project') except: messages.error(request, "Failed to Add Project!!!") return redirect('add_project')
class StripImgMetadataTest(TestCase): @classmethod def setUpTestData(cls): # NOTE: if you modify those elements they need to be created in setUp, instead of here cls.user = get_user_model().objects.create_user('a', 'b', 'c') def setUp(self): self.client.force_login(self.user) self.project = Project(creator=self.user, name_short='PRJ') self.project.save() self.project.manager.add(self.user) self.project.developer.add(self.user) # TODO create issue def test_change_avatar(self): # TODO TESTCASE change avatar - picture stripping pass def test_comment_with_picture(self): # TODO TESTCASE comment with picture from issue-detail - picture stripping pass def test_file_upload_picture(self): # TODO TESTCASE attachment from issue-detail - picture stripping pass
def add_new_project(request): #user validation start if not request.user.is_authenticated: return redirect("/login") if request.user.user_type == 1: return redirect("/university/home") #user validation end if request.method == 'POST': form = RegisterProject(request.POST) if form.is_valid(): admin = Company.objects.get(admin=request.user.pk) project = Project( project_name=form.cleaned_data['project_name'], project_description=form.cleaned_data['project_description'], developed_for=admin, start_date=form.cleaned_data['start_date'], end_date=form.cleaned_data['end_date'], bidding_start=form.cleaned_data['bidding_start'], bidding_end=form.cleaned_data['bidding_end'], ) project.save() messages.info( request, f"Project ' {project.project_name} ' pushed successfully!") return redirect('/company/home') # return render(request, 'company/index.html', context) else: context = {"form": form} return render(request, 'company/add_new_project.html', context) form = RegisterProject() context = {"form": form} return render(request, 'company/add_new_project.html', context)
class KanbancolTest(SeleniumTestCase): def setUp(self): # Uses the cookie hack from: # https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django client = Client() user = get_user_model().objects.create_user('a', 'b', 'c') client.login(username='******', password='******') self.cookie = client.cookies['sessionid'] self.short = "asdf" self.project = Project(creator=user, name="asdf", name_short=self.short) self.project.save() self.project.developer.set((user.pk, )) self.project.manager.set((user.pk, )) self.project.save() def test_create(self): self.selenium.get('{}{}'.format( self.live_server_url, reverse('kanbancol:create', kwargs={'project': self.short}))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie.value, 'secure': False, 'path': '/' }) self.selenium.refresh() self.selenium.get('{}{}'.format( self.live_server_url, reverse('kanbancol:create', kwargs={'project': self.short}))) field = self.selenium.find_element_by_name("name") field.send_keys('Palimpalim') self.selenium.find_element_by_css_selector('.save').click() self.assertEqual(self.selenium.title, 'Edit asdf') def test_delete_column_and_test_in_project_edit(self): # TODO TESTCASE pass def test_create_column_and_test_in_project_edit(self): # TODO TESTCASE pass def test_move_column_up_in_project_edit(self): # TODO TESTCASE pass def test_change_number_of_columns_and_test(self): # TODO TESTCASE # TODO create some # TODO delete some of the first ones # TODO verify everything works as expected pass def test_delete_todo_column_and_stop_running_sprint(self): # TODO TESTCASE # TODO what happens with those issues? pass
def get(self, request, version=None): project_query = request.GET.get('project') fields_query = request.GET.get('fields') projects = Project.get_for(request.user) if project_query: projects = projects.filter(id__in=project_query.split(',')) fields = None if fields_query: fields = fields_query.split(',') options = {} def _filter_by_projects(qs, projects): for p in projects: qs = qs.filter(project=p) return qs if (fields is None or 'created_by' in fields): created_by = _filter_by_projects(User.objects, projects) options['created_by'] = [{ 'key': user.id, 'value': user.profile.get_display_name(), } for user in created_by.distinct()] if (fields is None or 'project' in fields): projects = Project.get_for(request.user) options['project'] = [{ 'key': project.id, 'value': project.title, } for project in projects.distinct()] return response.Response(options)
def createProject(request): if request.method == 'POST': projectName = request.POST.get("projectName", "") projectDescribe = request.POST.get("projectDescribe", "") projectStatus = request.POST.get("projectStatus", "") username = request.session.get('username', "") userLevel = User.objects.get(username=username) if userLevel.level == 'visitors': return JsonResponse({"code": 0, "massage": "权限不足"}) if userLevel.level == 'admin': project1 = Project() project1.p_name = projectName project1.p_describe = projectDescribe project1.p_status = projectStatus now = int(time.time()) timeArray = time.localtime(now) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) project1.p_createtime = otherStyleTime project1.p_updatetime = otherStyleTime project1.p_exists = "True" print(userLevel.level) project1.save() appLog.info( "log/projectOperation.log", username + "创建了一个项目:" + projectName + ",项目描述:" + projectDescribe + "项目状态:" + projectStatus) return JsonResponse({"code": 200, "massage": "成功"}) else: return JsonResponse({"code": 0, "massage": "权限不足"}) else: return JsonResponse({"code": 0, "massage": "请求异常"})
def test_edit_ballot(self): proj = Project(name='test',order=0, doc_type='STD', description='test edit ballot', task_group='TGx', par_date=datetime.datetime.now()) proj.save() bal = Ballot(number=123,project=proj, ballot_type=Ballot.WGInitial.code, draft='1.0', opened=datetime.datetime.now(), pool=100) bal.closed = bal.opened + datetime.timedelta(days=15) bal.save() url = reverse('ballot.views.edit_ballot',args=[bal.number]) response = self._check_page(url) data = response.context['form'].initial for key in data.keys(): if data[key] is None: data[key] = '' data['curpk'] = bal.pk data['draft'] = '2.0' data['submit']='Save' form = BallotForm(data, instance=bal) valid = form.is_valid() self.failUnless(valid) response = self.client.post(url,data) self.failIf(response.status_code!=302 and response.status_code!=303) self.failUnlessEqual(Ballot.objects.count(),1) bal = Ballot.objects.get(pk=123) self.failUnlessEqual(float(bal.draft),2.0) # test renumbering the ballot, which should cause the old ballot object to be deleted data['number'] = 125 form = BallotForm(data, instance=bal) valid = form.is_valid() self.failUnless(valid) response = self.client.post(url,data) self.failIf(response.status_code!=302 and response.status_code!=303) self.failUnlessEqual(Ballot.objects.count(),1) bal = Ballot.objects.get(pk=125) self.failUnlessRaises(Ballot.DoesNotExist,Ballot.objects.get,pk=123)
def setUp(self): self.user = get_user_model().objects.create_user('a', 'b', 'c') self.project = Project(name="Fancy Project", name_short="FYP", description="Fancy description", creator=self.user) self.project.save() self.project.developer.add(self.user) self.project2 = Project(name="plain Project", name_short="plai", creator=self.user) self.project2.save() self.project2.developer.add(self.user) # Uses the cookie hack from: # https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django client = Client() client.login(username='******', password='******') self.cookie = client.cookies['sessionid'] self.selenium.get("{}{}".format(self.live_server_url, reverse('invite_users:invite_users'))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie.value, 'secure': False, 'path': '/' }) self.selenium.refresh()
def setUp(self): self.user = get_user_model().objects.create_user( 'test', '*****@*****.**', 'test') self.project = Project(creator=self.user, name_short='PRJ') self.project.save() self.project.developer.add(self.user) # NOTE: those elements get modified by some of those tests, so this shall NOT be created in setUpTestData() self.issue = Issue(title='issue title', project=self.project, due_date='2016-12-16', storypoints='3') self.issue.save() self.issue2 = Issue(title='title2', project=self.project, due_date='2016-12-16', storypoints='3') self.issue2.save() self.issue.assignee.add(self.user) # Uses the cookie hack from: # https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django client = Client() client.login(username='******', password='******') self.cookie = client.cookies['sessionid'] self.selenium.get("{}{}".format(self.live_server_url, reverse('timelog:loginfo'))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie.value, 'secure': False, 'path': '/' }) self.selenium.refresh()
def setUp(self): self.client.force_login(self.user) # NOTE: these elements get modified by some testcases, so they should NOT be created in setUpTestData() self.project = Project(creator=self.user, name_short='PRJ', activity_only_for_managers=False) self.project.save() self.project.developer.add(self.user) self.project2 = Project(creator=self.user, activity_only_for_managers=True, name_short='PRJJ') self.project2.save() self.project2.manager.add(self.user) self.project2.developer.add(self.user, self.user2) self.kanbancol = KanbanColumn(project=self.project, position=4, name='test') self.kanbancol.save() self.issue = Issue(title='a very very very very very very very long issue title', project=self.project, due_date='2016-12-16', kanbancol=self.kanbancol, storypoints='3' ) self.issue.save() self.issue.assignee.add(self.user) self.issue2 = Issue(title='second_issue', project=self.project) self.issue2.save() self.issue2.assignee.add(self.user) self.time = now().strftime("%Y-%m-%d %H:%M:%S") # success logedit_address_kwargs self.sqn_l1_address_kwarg = {"project": self.issue.project.name_short, "sqn_i": self.issue.number, "sqn_l": 1 }
def setUp(self): # Uses the cookie hack from: # https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django client = Client() self.user = get_user_model().objects.create_user('a', 'b', 'c') client.login(username='******', password='******') self.cookie = client.cookies['sessionid'] self.selenium.get("{}{}".format(self.live_server_url, "/")) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie.value, 'secure': False, 'path': '/' }) self.selenium.refresh() self.short = "asdf" self.project = Project(creator=self.user, name="long_asdf", name_short=self.short) self.project.save() self.project.developer.set((self.user.pk, )) self.project.manager.set((self.user.pk, )) self.project.save() si = SlackIntegration() si.project = self.project si.api_token = "foo" si.channel = "channel" si.save() self.title_name = 'This is title' self.comment = "This is comment"
class JobTestCase(TestCase): def setUp(self): self.org = Organization() self.org.save() self.org2 = Organization() self.org2.save() self.project = Project(organization=self.org) self.project.save() self.workstream = Workstream(project=self.project) self.workstream.save() self.status1 = JobStatus(organization=self.org) self.status1.save() self.status2 = JobStatus(organization=self.org2) self.status2.save() self.job = Job(workstream=self.workstream, status=self.status1) self.job.save() def tearDown(self): self.org.delete() self.org2.delete() def test__job_workstream__matches(self): self.assertEqual(self.workstream, self.job.workstream) def test__save__throws_when_org_doesnt_match_workstream(self): job = Job(workstream=self.workstream, status=self.status2) self.assertRaises(PermissionDenied, lambda: job.save())
def create(request): if request.method == 'POST': form = CreateForm(request.POST, request.FILES) if form.is_valid(): project = Project( author=request.user, name=form.cleaned_data['name'], description=form.cleaned_data['description'], status=form.cleaned_data['status'], area=form.cleaned_data['area'], website=form.cleaned_data['website'], image=form.cleaned_data['image'] ) project.save() return redirect( request, 'project-read', [project.id], {request.url_name: 'True'} ) else: form = CreateForm() params = {'form': form} params.update(csrf(request)) return response(request, params)
def setUp(self): self.client.force_login(self.user) # NOTE: this element gets modified by some of those tests, so this shall NOT be created in setUpTestData() self.project = Project(creator=self.user, name_short='PRJ') self.project.save() self.project.developer.add(self.user) self.project.developer.add(self.user2) # NOTE: this element gets modified by some of those tests, so this shall NOT be created in setUpTestData() self.kanbancol = KanbanColumn(project=self.project, position=4, name='test') self.kanbancol.save() # NOTE: this element gets modified by some of those tests, so this shall NOT be created in setUpTestData() self.issue = Issue( title='a very very very very very very very long issue title', project=self.project, due_date='2016-12-16', kanbancol=self.kanbancol, storypoints='3') self.issue.save() self.issue2 = Issue(title='issue title', project=self.project, due_date='2016-12-16', kanbancol=self.kanbancol, storypoints='3') self.issue2.save() self.issue.assignee.add(self.user)
def setUp(self): self.client.force_login(self.user) # NOTE: this element gets modified by some of those tests, so this shall NOT be created in setUpTestData() self.project = Project(creator=self.user, name_short='PRJ', activity_only_for_managers=False) self.project.save() self.project.developer.add(self.user) self.project2 = Project(creator=self.user, activity_only_for_managers=True, name_short='PRJJ') self.project2.save() self.project2.manager.add(self.user) self.project2.developer.add(self.user, self.user2) # NOTE: this element gets modified by some of those tests, so this shall NOT be created in setUpTestData() self.kanbancol = KanbanColumn(project=self.project, position=4, name='test') self.kanbancol.save() # NOTE: this element gets modified by some of those tests, so this shall NOT be created in setUpTestData() self.issue = Issue(title='a very very very very very very very long issue title', project=self.project, due_date='2016-12-16', kanbancol=self.kanbancol, storypoints='3' ) self.issue.save() self.issue.assignee.add(self.user) self.issue2 = Issue(title='second_issue', project=self.project) self.issue2.save() self.issue2.assignee.add(self.user) self.time = now().strftime("%Y-%m-%d %H:%M:%S")
def setUp(self): self.user = get_user_model().objects.create_user( 'a_user', '*****@*****.**', 'a1234568') self.project = Project(name="Projectname", name_short="proj", creator=self.user) self.project.save() self.project.manager.add(self.user) self.short = self.project.name_short tag = Tag(project=self.project, tag_text="foo") tag.save() Issue(project=self.project, title="a").save() issue = Issue(project=self.project, title="b") issue.save() issue.tags.add(tag) # Uses the cookie hack from: # https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django client = Client() client.login(username='******', password='******') self.cookie = client.cookies['sessionid'] self.selenium.get("{}{}".format(self.live_server_url, reverse('invite_users:invite_users'))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie.value, 'secure': False, 'path': '/' }) self.selenium.refresh()
def setUp(self): # NOTE: these elements get modified by some testcases, so they should NOT be created in setUpTestData() self.project = Project(creator=self.user1, name_short='asdf') self.project.save() self.project.developer.add(self.user1) self.project.developer.add(self.user2) self.project.manager.add(self.user1) self.project2 = Project(creator=self.user2, name_short='asdg') self.project2.save() self.project2.manager.add(self.user2) self.issue = Issue(title='test', project=self.project) self.issue.save() self.issue2 = Issue(title='test', project=self.project2) self.issue2.save() self.comment = Comment(text='test', creator=self.user1, issue=self.issue) self.comment.save() self.comment2 = Comment(text='test', creator=self.user2, issue=self.issue2) self.comment2.save() self.log = Timelog(time=datetime.timedelta(hours=2), user=self.user1, issue=self.issue) self.log.save() self.log2 = Timelog(time=datetime.timedelta(hours=2), user=self.user2, issue=self.issue2) self.log2.save() self.user1_auth = 'Basic ' + base64.b64encode('user1:c'.encode()).decode() self.user2_auth = 'Basic ' + base64.b64encode('user2:c'.encode()).decode() self.client.credentials(HTTP_AUTHORIZATION=self.user1_auth)
def setUp(self): self.user = get_user_model().objects.create_user('a', 'b', 'c') self.user2 = get_user_model().objects.create_user('d', 'e', 'f') self.project = Project(creator=self.user, name="Selenium-Project", name_short="SLN") self.project.save() self.project.developer.add(self.user) self.project.developer.add(self.user2) self.project.manager.add(self.user) self.issue = Issue(title="Test-Issue", project=self.project, kanbancol=self.project.kanbancol.first(), type="Bug") self.issue.save() # Uses the cookie hack from: # https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django client = Client() client.login(username='******', password='******') self.cookie = client.cookies['sessionid'] self.selenium.get("{}{}".format(self.live_server_url, reverse('invite_users:invite_users'))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie.value, 'secure': False, 'path': '/' }) self.selenium.refresh()
def setUp(self): self.client.force_login(self.user) # NOTE: these elements get modified by some testcases, so they should NOT be created in setUpTestData() self.project = Project(creator=self.user, name_short='PRJ') self.project.save() self.issue = Issue(title="Test-Issue", project=self.project, type="Bug") self.issue.save()
def project_create(request): #template_project = Project() #form = ProjectForm(request.POST or template_project) form = ProjectForm(request.POST or None, initial={}) if form.is_valid(): new_project = Project(title=form.cleaned_data['title'], description=form.cleaned_data['description'], url=form.cleaned_data['url'], open=form.cleaned_data['open']) new_project.save() #new_project = form.save() new_position = admin_position_default new_position.project = new_project new_position.save() relation = ProjectRelation(admin=True, user=request.user.userdata, project=new_project) relation.save() new_position.project_relation = relation new_position.save() admin_position_default.id=None for interest in form.cleaned_data['interests']: pi = ProjectInterest(project=new_project, interest=interest) pi.save() return redirect(project_detail, new_project.id) return render_to_response('project/create.html', {'form': form}, context_instance=RequestContext(request))
def setUp(self): self.org = Organization() self.org.save() self.project = Project(organization=self.org) self.project.save() self.workstream = Workstream(project=self.project) self.workstream.save()
def create_project_form(request): """ Form to create a new project """ # First we check to see the site has been set up, otherwise we throw the user to the config screen if not bool(os.path.isdir(Project.project_options.repository_directory)): request.user.message_set.create(message="The site has not been set up yet. Log in as your admin user and create your settings!") return HttpResponseRedirect(reverse('site-config')) if request.is_ajax(): template ='project/project_create_ajax.html' else: template = 'project/project_create.html' # Lets check if this form is being shown or processed if request.method == "POST": # We're processing the form, so lets create the instance form = NewProjectForm(request.POST, auto_id=False) # The form is correct, lets proceeed. if form.is_valid(): # Lets check the user has conformed to a sites T&C's if form.cleaned_data['t_and_c'] == True: # Create the project instance project = Project( project_id = string.lower(form.cleaned_data['project_id']), project_name = form.cleaned_data['project_name'], short_description = form.cleaned_data['short_description'], full_description = form.cleaned_data['full_description'], project_manager = request.user, hgweb_style = form.cleaned_data.get('hgweb_style', ''), project_icon = form.cleaned_data['project_icon'], ) # Ok, we're all good, so lets save. project.save() # We'll tell the user that there site has been saved request.user.message_set.create(message=_("The project " + form.cleaned_data['project_name'] + " has been created")) if request.is_ajax(): return HttpResponse( "{'success': 'true', 'url': '" + reverse('project-detail', kwargs={'slug':form.cleaned_data['project_id']}) + "', 'project': " + json_encode(project) + "}" , mimetype="application/json") else: return HttpResponseRedirect(reverse('project-detail', kwargs={'slug': form.cleaned_data['project_id']})) else: return render_to_response(template, { 'form':form.as_table(), }, context_instance=RequestContext(request) ) #return HttpResponseRedirect(reverse('project-detail', kwargs={'slug':form.cleaned_data['name_short']})) else: form = NewProjectForm() is_auth = request.user.is_authenticated() return render_to_response(template, { 'form':form.as_table(), 'is_auth': is_auth }, context_instance=RequestContext(request) )
def setUp(self): self.user = get_user_model().objects.create_user('a', 'b', 'c') self.project = Project(creator=self.user, name="asdf", name_short="PRJ") self.project.save() self.project.manager.add(self.user) self.project.developer.add(self.user) self.project2 = Project(creator=self.user, name="2ndproj", name_short="PRJ2") self.project2.save() self.project2.developer.add(self.user) self.kanban = KanbanColumn(name='KanCol', project=self.project2, position=4) self.kanban.save() # Uses the cookie hack from: # https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django client = Client() client.login(username='******', password='******') self.cookie = client.cookies['sessionid'] self.selenium.get("{}{}".format(self.live_server_url, reverse('invite_users:invite_users'))) self.selenium.add_cookie({ 'name': 'sessionid', 'value': self.cookie.value, 'secure': False, 'path': '/' }) self.selenium.refresh()
def setUp(self): self.client.force_login(self.user) # NOTE: these elements get modified by some testcases, so they should NOT be created in setUpTestData() self.project = Project(creator=self.user, name_short='PRJ') self.project.save() self.project.manager.add(self.user) self.project.developer.add(self.user)
def test_leave_project(self): new_project = Project(name='asdf', name_short='asd', creator=self.user) new_project.save() new_project.manager.add(self.user) user2 = get_user_model().objects.create_user('test2', '*****@*****.**', 'test1234') response = self.client.post(reverse('project:leave', kwargs={'project': 'asd'}), {'delete': ''}, follow=True) self.assertRedirects( response, reverse('project:edit', kwargs={'project': 'asd'})) self.assertContains(response, 'last manager') new_project.developer.add(user2) response = self.client.post(reverse('project:leave', kwargs={'project': 'asd'}), {'delete': ''}, follow=True) self.assertRedirects( response, reverse('project:edit', kwargs={'project': 'asd'})) self.assertContains(response, 'last manager') new_project.manager.add(user2) response = self.client.post(reverse('project:leave', kwargs={'project': 'asd'}), {'delete': ''}, follow=True) self.assertRedirects(response, reverse('project:list')) self.assertNotIn(self.user, new_project.get_members())
def setUp(self): self.base_domain = 'aber.ac.uk' self.user = CustomUser.objects.create( username='******'.format(self.base_domain), email='user@{}'.format(self.base_domain) ) self.user.save() self.user2 = CustomUser.objects.create( username='******'.format(self.base_domain), email='user2@{}'.format(self.base_domain) ) self.user2.save() self.project = Project( title="Project title", description="Project description", tech_lead=self.user, # category=ProjectCategory.objects.get(pk=1) ) self.project.save() self.membership = ProjectUserMembership.objects.create( user=self.user2, project=self.project, date_joined='2019-07-31' ) self.membership.save()
def test_delete_ballot(self): proj = Project(name='test',order=0, doc_type='STD', \ description='test_delete_ballot', task_group='TGx', \ par_date=datetime.datetime.now()) proj.save() bal = Ballot(number=123,project=proj, draft='1.0', \ opened=datetime.datetime.now(), pool=100, \ ballot_type=Ballot.WGInitial.code) bal.closed = bal.opened + datetime.timedelta(days=15) bal.save() self.failUnlessEqual(bal.pk, 123) self.failUnlessEqual(Ballot.objects.count(), 1) url = reverse('ballot.views.main_page', args=[]) response = self._check_page(url) self.failUnlessEqual(Ballot.objects.count(), 1) self.wait_for_backlog_completion(DenormalizedBallot, 10) run_test_task_queue(self.client) self.failUnlessEqual(Ballot.objects.count(), 1) dn = DenormalizedBallot.objects.get(pk=bal.pk) self.failIfEqual(dn, None) self.failUnlessEqual(Ballot.objects.count(), 1) Ballot.objects.filter(pk=bal.number).delete() run_test_task_queue(self.client) self.failUnlessRaises(DenormalizedBallot.DoesNotExist, DenormalizedBallot.objects.get, pk=123) bal = Ballot(number=124,project=proj, draft='2.0', opened=datetime.datetime.now(), \ pool=100, ballot_type=Ballot.WGInitial.code) bal.closed = bal.opened + datetime.timedelta(days=15) bal.save() run_test_task_queue(self.client) url = reverse('ballot.views.edit_ballot', args=[bal.number]) response = self._check_page(url) data = response.context['form'].initial for key in data.keys(): if data[key] is None: data[key] = '' data['curpk'] = bal.pk data['delete'] = 'Delete' form = BallotForm(data, instance=bal) valid = form.is_valid() self.failUnless(valid) response = self.client.post(url, data) self.failIf(response.status_code != 302 and response.status_code != 303) url = reverse('del_ballot', args=[bal.number]) response.get('Location').index(url) response = self._check_page(url) match = re.search(r'input\s+type="submit"\s+name="confirm"', str(response), re.IGNORECASE) self.assertTrue(match) data = {"confirm": "Yes, I'm sure"} response = self.client.post(url, data) self.failIf(response.status_code != 302 and response.status_code != 303) self.failUnlessRaises(Ballot.DoesNotExist, Ballot.objects.get, pk=124) run_test_task_queue(self.client) self.failUnlessRaises(DenormalizedBallot.DoesNotExist, DenormalizedBallot.objects.get, pk=124)
class SprintTest(SeleniumTestCase): def setUp(self): self.user = get_user_model().objects.create_user('a', 'b', 'c') self.project = Project(name="Fancy Project", name_short="FYP", description="Fancy description", creator=self.user) self.project.save() self.project.developer.add(self.user) self.project2 = Project(name="plain Project", name_short="plai", creator=self.user) self.project2.save() self.project2.developer.add(self.user) # Uses the cookie hack from: # https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django client = Client() client.login(username='******', password='******') self.cookie = client.cookies['sessionid'] self.selenium.get("{}{}".format(self.live_server_url, reverse('invite_users:invite_users'))) self.selenium.add_cookie({'name': 'sessionid', 'value': self.cookie.value, 'secure': False, 'path': '/'}) self.selenium.refresh() def test_reachable_and_elements_exist(self): # TODO TESTCASE # TODO backlog # TODO edit sprint # TODO sprintboard pass def test_create_sprint(self): # TODO TESTCASE pass def test_edit_sprint(self): # TODO TESTCASE pass def test_assign_issue_to_sprint(self): # TODO TESTCASE pass def test_remove_issue_form_sprint(self): # TODO TESTCASE pass def test_start_sprint(self): # TODO TESTCASE pass def test_stop_sprint(self): # TODO TESTCASE pass def test_sprintboard(self): # TODO TESTCASE (switch cols) pass def test_backlog(self): # TODO TESTCASE pass
def test_add_member_to_project(self): owner = User.objects.all()[0] category = Category.objects.all()[0] project = Project(name="sdn project", owner=owner, category=category) project.save() self.assertTrue(project.memberships.count() == 1) #: there is a default member which is the owner project.add_member(User.objects.all()[1]) self.assertTrue(project.memberships.count() == 2)
def setUp(self): self.project = Project(creator=self.user, name_short='PRJ') self.project.save() self.project.developer.add(self.user) # TODO hopefully this will correctly create this sprint as already completed. self.sprint = Sprint(project=self.project, seqnum=3, startdate='2016-03-04', enddate='2016-03-05') self.sprint.save() self.client.force_login(self.user)
def test_board_order_by(self): # driver.find_element_by_id("dropdownMenu1").click() # driver.find_element_by_link_text("Sprint 1").click() # create project and issues driver = self.selenium project = Project(name='TestProjekt', name_short='TP', creator=self.user) project.save() project.developer.add(self.user) issue1 = Issue(project=project, title="TestIssue1", priority=4, type='Story') issue2 = Issue(project=project, title="TestIssue2", priority=0, type='Bug') issue3 = Issue(project=project, title="TestIssue3", priority=3, type='Task') issue4 = Issue(project=project, title="TestIssue3", priority=2, type='Task') issue5 = Issue(project=project, title="TestIssue3", priority=0, type='Story') issue1.save() issue2.save() issue3.save() issue4.save() issue5.save() # check order_by number driver.get("{}{}".format(self.live_server_url, reverse('sprint:sprintboard', kwargs={'project': project.name_short} ))) col = driver.find_element_by_id("sortable0") issues = col.find_elements_by_class_name("issuecard") for i in range(len(issues)-1): self.assertEqual(issues[i].get_attribute("id") < issues[i+1].get_attribute("id"), True) # check order_by priority driver.get("{}{}".format(self.live_server_url, reverse('sprint:sprintboard', kwargs={'project': project.name_short} ))+"?order_by=priority") col = driver.find_element_by_id("sortable0") issues = col.find_elements_by_class_name("issuecard") for i in range(len(issues)-1): self.assertEqual(issues[i].get_attribute("data-priority") >= issues[i+1].get_attribute("data-priority"), True) # check order_by title driver.get("{}{}".format(self.live_server_url, reverse('sprint:sprintboard', kwargs={'project': project.name_short} ))+"?order_by=title") col = driver.find_element_by_id("sortable0") issues = col.find_elements_by_class_name("issuecard") for i in range(len(issues)-1): self.assertEqual(issues[i].get_attribute("data-title") <= issues[i+1].get_attribute("data-title"), True) # check order_by Type driver.get("{}{}".format(self.live_server_url, reverse('sprint:sprintboard', kwargs={'project': project.name_short} ))+"?order_by=type") col = driver.find_element_by_id("sortable0") issues = col.find_elements_by_class_name("issuecard") for i in range(len(issues)-1): self.assertEqual(issues[i].get_attribute("data-type") <= issues[i+1].get_attribute("data-type"), True)
class ProjectNotificationTests(TestCase): fixtures = ['institution/fixtures/institutions.json'] def setUp(self): self.base_domain = 'aber.ac.uk' self.user = CustomUser.objects.create( username=f'user@{self.base_domain}', email=f'user@{self.base_domain}') self.user.save() self.user2 = CustomUser.objects.create( username=f'user2@{self.base_domain}', email=f'user2@{self.base_domain}') self.user2.save() self.project = Project( title="Project title", description="Project description", tech_lead=self.user, # category=ProjectCategory.objects.get(pk=1) ) self.project.save() self.membership = ProjectUserMembership.objects.create( user=self.user2, project=self.project, date_joined='2019-07-31') self.membership.save() def test_project_created_notification_default_email(self): notifications.project_created_notification(self.project) assert len(mail.outbox) > 0, "An email must be sent" assert len(mail.outbox) == 1, "Only one email must be sent" assert len(mail.outbox[0].to) == 1,\ 'Mail should be sent to one recipient' assert mail.outbox[0].to[0] == settings.DEFAULT_SUPPORT_EMAIL,\ f'Wrong recipient: {mail.outbox[0].to}' def test_project_created_notification_institution_email(self): from institution.models import Institution uni = Institution.objects.get(base_domain=self.base_domain) uni.support_email = f'support@{self.base_domain}' uni.save() notifications.project_created_notification(self.project) assert len(mail.outbox) > 0, "An email must be sent" assert len(mail.outbox) == 1, "Only one email must be sent" assert len(mail.outbox[0].to) == 1,\ 'Mail should be sent to one recipient' assert mail.outbox[0].to[ 0 ] == uni.support_email, \ f'Wrong recipient: {mail.outbox[0].to}' def test_project_membership_created(self): membership = ProjectUserMembership.objects.get(pk=1) notifications.project_membership_created(self.membership) assert len(mail.outbox) > 0, "An email must be sent" assert len(mail.outbox) == 1, "Only one email must be sent"
def setUpTestData(cls): # NOTE: if you modify these elements they need to be created in setUp(), instead of here cls.user = get_user_model().objects.create_user('a', 'b', 'c') cls.project = Project(creator=cls.user, name_short='PRJ') cls.project.save() cls.project.developer.add(cls.user) cls.project2 = Project(creator=cls.user, name_short='PRO') cls.project2.save()
def projects_new_view(request): #TODO - check permissions try: o = Project(title=request.GET['title'], description=request.GET['description'], created_by=request.user) o.save() auth, created = ProjectAuthLevel.objects.get_or_create(task_add=True, task_edit=True, subproject_add=True, subproject_edit=True) no = ProjectMembership(project=o, user=request.user, level=auth) no.save() except: return HttpResponse("Something went wrong!") return HttpResponse("1")
def get_mock_project(title): """ Generate project. :return Project: """ p = Project( title=title ) p.save() return p
def test_delete_ballot(self): proj = Project(name='test',order=0, doc_type='STD', \ description='test_delete_ballot', task_group='TGx', \ par_date=datetime.datetime.now()) proj.save() bal = Ballot(number=123,project=proj, draft='1.0', \ opened=datetime.datetime.now(), pool=100, \ ballot_type=Ballot.WGInitial.code) bal.closed = bal.opened + datetime.timedelta(days=15) bal.save() self.failUnlessEqual(bal.pk,123) self.failUnlessEqual(Ballot.objects.count(),1) url = reverse('ballot.views.main_page',args=[]) response = self._check_page(url) self.failUnlessEqual(Ballot.objects.count(),1) self.wait_for_backlog_completion(DenormalizedBallot, 10) run_test_task_queue(self.client) self.failUnlessEqual(Ballot.objects.count(),1) dn = DenormalizedBallot.objects.get(pk=bal.pk) self.failIfEqual(dn,None) self.failUnlessEqual(Ballot.objects.count(),1) Ballot.objects.filter(pk=bal.number).delete() run_test_task_queue(self.client) self.failUnlessRaises(DenormalizedBallot.DoesNotExist, DenormalizedBallot.objects.get, pk=123) bal = Ballot(number=124,project=proj, draft='2.0', opened=datetime.datetime.now(), \ pool=100, ballot_type=Ballot.WGInitial.code) bal.closed = bal.opened + datetime.timedelta(days=15) bal.save() run_test_task_queue(self.client) url = reverse('ballot.views.edit_ballot',args=[bal.number]) response = self._check_page(url) data = response.context['form'].initial for key in data.keys(): if data[key] is None: data[key] = '' data['curpk'] = bal.pk data['delete']='Delete' form = BallotForm(data, instance=bal) valid = form.is_valid() self.failUnless(valid) response = self.client.post(url,data) self.failIf(response.status_code!=302 and response.status_code!=303) url = reverse('del_ballot',args=[bal.number]) response.get('Location').index(url) response = self._check_page(url) match = re.search(r'input\s+type="submit"\s+name="confirm"', str(response), re.IGNORECASE) self.assertTrue(match) data = {"confirm":"Yes, I'm sure"} response = self.client.post(url,data) self.failIf(response.status_code!=302 and response.status_code!=303) self.failUnlessRaises(Ballot.DoesNotExist, Ballot.objects.get, pk=124) run_test_task_queue(self.client) self.failUnlessRaises(DenormalizedBallot.DoesNotExist, DenormalizedBallot.objects.get, pk=124)
class CreateTest(TestCase): def setUp(self): self.client = Client() self.username = '******' self.email = '*****@*****.**' self.passwd = 'passwd' self.text = 'Message text...' user = User.objects.create_user(self.username, self.email, self.passwd) self.project = Project(author=user) self.project.save() self.client.login(username=self.username, password=self.passwd) def test_login_required(self): self.client.logout() response = self.client.get(CREATE_URL % self.project.id) self.assertRedirects(response, LOGIN_URL + '?next=' + \ CREATE_URL % self.project.id) def test_get(self): response = self.client.get(CREATE_URL % self.project.id) self.assertEqual(response.status_code, 200) def test_post(self): self.client.post(CREATE_URL % self.project.id, {'text': self.text}) message = Message.objects.get(author__username=self.username) self.assertEqual(message.is_active, True) self.assertEqual(message.created, date.today()) self.assertEqual(message.project, self.project) self.assertEqual(message.text, self.text) def test_next(self): response = self.client.post(CREATE_URL % self.project.id + '?next=' + LOGIN_URL, {'text': self.text}) self.assertRedirects(response, LOGIN_URL + '?message-create=True') def test_deactivated_project(self): self.project.is_active = False self.project.save() response = self.client.get(CREATE_URL % self.project.id) self.assertEqual(response.status_code, 404) def test_deactivated_project_author(self): username = '******' email = '*****@*****.**' passwd = 'abc' user = User.objects.create_user(username, email, passwd) self.client.logout() self.client.login(username=username, password=passwd) self.project.author.is_active = False self.project.author.save() response = self.client.get(CREATE_URL % self.project.id) self.assertEqual(response.status_code, 404)
def test_add_remove_project(self): self.failUnlessEqual(Project.objects.count(),0) proj = Project(name='test',order=0, doc_type='STD', description='test_add_remove_project', task_group='TGx', par_date=datetime.datetime.now()) proj.save() self.failUnlessEqual(Project.objects.count(),1) run_test_task_queue(self.client) self.failUnlessEqual(Project.objects.count(),1) self.failUnlessEqual(DenormalizedProject.objects.count(),1) dn = DenormalizedProject.objects.get(pk=proj.pk) self.failIfEqual(dn,None) self.failUnlessEqual(Project.objects.count(),1) proj.delete() self.failUnlessEqual(Project.objects.count(),0) run_test_task_queue(self.client) self.failUnlessEqual(DenormalizedProject.objects.count(),0)
def add_like(cls, project_id, scientist_id): project = yield Project.get_by_id(project_id) project.likes += 1 scientist = yield Scientist.get_by_id(scientist_id) scientist.liked_projects = list(set(scientist.liked_projects.append(project_id))) yield project.save(fields=['likes']) yield scientist.save(fields=['liked_projects'])
def delete(cls, project_id): """ Удалить участников, удалить вакансии, поставить статус откликам - удаленные. У ученого убрать из managing_project_ids. """ project = yield Project.get_by_id(project_id) for participant_id in project.participants: yield cls.delete_participant(participant_id) for vacancy_id in project.vacancies: yield cls.delete_vacancy(vacancy_id) for response_id in project.responses: yield cls.set_del_status_response(response_id) scientist = yield Scientist.get_by_id(project.manager_id) scientist.managing_project_ids.remove(project_id) yield scientist.save(fields=[u'managing_project_ids'], columns=[u'managing_project_ids']) yield Project.delete(project_id, tbl=Project.TABLE)
def delete_like(cls, project_id, scientist_id): project = yield Project.get_by_id(project_id) project.likes -= 1 scientist = yield Scientist.get_by_id(scientist_id) scientist.liked_projects.remove(project_id) yield project.save(fields=['likes']) yield scientist.save(fields=['liked_projects'])
def get_my_projects(cls, manager_id): scientist_columns = [u'managing_project_ids'] scientist_json = yield Scientist.get_json_by_id(manager_id, columns=scientist_columns) # [{scientist_id, vacancy_id, message}] project_ids = scientist_json.get(u'managing_project_ids', []) if not project_ids: raise gen.Return([]) projects = [] for project_id in project_ids: project_columns = [u'title', u'responses'] project_json = yield Project.get_json_by_id(project_id, columns=project_columns) project_json.update(project_id=project_id) raw_responses = project_json.pop(u'responses', []) if not raw_responses: project_json.update(responses=[]) projects.append(project_json) continue responses = [] for response in raw_responses: response_data = yield cls.get_response_data(response) responses.append(response_data) project_json.update(responses=responses) projects.append(project_json) raise gen.Return(projects)
def get_context_data(self, *args, **kwargs): ctx = super(Index, self).get_context_data(*args, **kwargs) ctx['top_projects'] = Project.top(3) ctx["all_projects"] = Project.latests(7) # Latests project bigger need needs = [] for p in Project.latests(4): need = p.things.all().order_by("quantity") if not need: continue needs.append(need[0]) ctx["needs"] = needs ctx["donnors"] = Donation.objects.all().order_by('-shipping__created') return ctx
class ReadTest(TestCase): def setUp(self): self.client = Client() self.username = '******' self.email = '*****@*****.**' self.passwd = 'passwd' self.title = 'Test' self.area = 'DESIGN' self.description = 'Testing...' user = User.objects.create_user(self.username, self.email, self.passwd) self.project = Project(author=user) self.project.save() self.job = Job(project=self.project, title=self.title, area=self.area, description=self.description) self.job.save() self.client.login(username=self.username, password=self.passwd) def test_login_required(self): self.client.logout() response = self.client.get(READ_URL % self.job.id) self.assertRedirects(response, LOGIN_URL + '?next=' + READ_URL % self.job.id) def test_get(self): response = self.client.get(READ_URL % self.job.id) self.assertEqual(response.status_code, 200) def test_invalid_id(self): response = self.client.get(READ_URL % '2') self.assertEqual(response.status_code, 404) def test_deactivated_project(self): self.project.is_active = False self.project.save() response = self.client.get(READ_URL % self.job.id) self.assertEqual(response.status_code, 404) def test_deactivated_project_author(self): username = '******' email = '*****@*****.**' passwd = 'abc' user = User.objects.create_user(username, email, passwd) self.client.logout() self.client.login(username=username, password=passwd) self.project.author.is_active = False self.project.author.save() response = self.client.get(READ_URL % self.job.id) self.assertEqual(response.status_code, 404)
def test_add_ballot(self): self.failUnlessEqual(Project.objects.count(),0) self.failUnlessEqual(Ballot.objects.count(),0) proj = Project(name='test',order=0, doc_type='STD', description='ballot test', task_group='TGx', par_date=datetime.datetime.now()) proj.save() self.failUnlessEqual(Project.objects.count(),1) url = reverse('ballot.views.add_ballot',args=[]) response = self._check_page(url) data = { 'project' : proj.pk, 'number':123, 'draft': 1.0, 'opened' : '2013-05-01', 'closed' : '2013-05-16', 'ballot_type' : Ballot.WGInitial.code, 'pool': 321, 'vote_for':'', 'vote_against':'', 'vote_abstain':'', 'vote_invalid':'', 'comments':'', 'instructions_url': 'http://grouper.ieee.org/instructions', 'draft_url': 'http://grouper.ieee.org/draft', 'redline_url':'', 'resolution_url':'', 'template_url': 'http://grouper.ieee.org/template', 'pool_url': 'http://grouper.ieee.org/pool', 'curstat': response.context['form'].initial['curstat'], 'curpk':'', 'submit':'Save' } response = self.client.post(url, data, follow=True) self.failUnlessEqual(response.status_code, 200) self.failUnlessEqual(Ballot.objects.count(),1) data['draft'] = 2.0 del data['submit'] data['cancel'] = 'Cancel' data['number'] += 1 response = self.client.post(url, data, follow=True) self.failUnlessEqual(response.status_code, 200) self.failUnlessEqual(Ballot.objects.count(),1) ballot = Ballot.objects.get(pk=123) self.failUnless(ballot.is_wg_ballot) self.failUnless(ballot.is_initial_ballot)
def post(self, *args, **kwargs): print u"search projects" search_data = json.loads(self.get_argument(u"data", u"{}")) print search_data try: response = yield Project.search(search_data[u"s_type"], search_data[u"s_query"]) except Exception, ex: logging.info("Exc on search projects:") logging.exception(ex) response = dict(message=ex.message)
def setUp(self): self.client = Client() self.username = '******' self.email = '*****@*****.**' self.passwd = 'passwd' self.text = 'Message text...' user = User.objects.create_user(self.username, self.email, self.passwd) self.project = Project(author=user) self.project.save() self.client.login(username=self.username, password=self.passwd)
def get_all(cls, columns=None): if not columns: columns = Project.OVERVIEW_FIELDS projects_data = yield Project.get_all_json(columns=columns) for project in projects_data: if u'research_fields' in project: project.update(research_fields= [dict(id=f, name=globals.SCIENCE_FIELDS_MAP[f]) for f in project[u'research_fields'] if f in globals.SCIENCE_FIELDS_MAP]) raise gen.Return(projects_data)
def test_edit_project(self): proj = Project(name='test',order=0, doc_type=Project.Standard.code, description='test project', task_group='TGx', par_date=datetime.datetime.now()) proj.save() self.failIf(proj.slug is None) url = reverse('project.views.edit_project',args=[proj.slug]) response = self._check_page(url) data = response.context['form'].initial for key in data.keys(): if data[key] is None: data[key] = '' data['name'] = 'newname' data['submit']='Save' form = ProjectForm(data, instance=proj) valid = form.is_valid() self.failUnless(valid) response = self.client.post(url,data) self.failIf(response.status_code!=302 and response.status_code!=303) self.failUnlessEqual(Project.objects.count(),1) proj = Project.objects.get(pk=proj.pk) self.failUnlessEqual(proj.name,'newname')
def test_renumber_ballot(self): proj = Project(name='test',order=0, doc_type='STD', description='test_renumber_ballot', task_group='TGx', par_date=datetime.datetime.now()) proj.save() self.failUnlessEqual(Project.objects.count(),1) self.failUnlessEqual(Ballot.objects.count(),0) bal = Ballot(number=123,project=proj, draft='1.0', opened=datetime.datetime.now(), pool=100) bal.closed = bal.opened + datetime.timedelta(days=15) bal.save() self.failUnlessEqual(Ballot.objects.count(),1) url = reverse('ballot.views.main_page',args=[]) self._check_page(url) #response = self.client.get(url) self.wait_for_backlog_completion(DenormalizedBallot, 10) dn = DenormalizedBallot.objects.get(pk=bal.pk) bal2 = Ballot.objects.get(number=bal.number) bal2.number = 321 bal2.save() Ballot.objects.get(number=123).delete() self.wait_for_backlog_completion(DenormalizedBallot, 10) self.failUnlessRaises(DenormalizedBallot.DoesNotExist, DenormalizedBallot.objects.get, number=123) dn = DenormalizedBallot.objects.get(number=bal2.number)
def setUp(self): self.client = Client() self.username = '******' self.email = '*****@*****.**' self.passwd = 'passwd' self.title = 'Test' self.area = 'DESIGN' self.description = 'Testing...' user = User.objects.create_user(self.username, self.email, self.passwd) self.project = Project(author=user) self.project.save() self.client.login(username=self.username, password=self.passwd)
def create_project(org, name): p = Project() p.name = name p.description = v = paragraphs(random.randint(2, 6)) p.ong = org p.shipping_address = paragraphs(1) p.created = timezone.now() + datetime.timedelta(random.randint(-360, 0)) p.save() for i in range(random.randint(1, 10)): create_thing(p, "thing%d" % (i+1))
def test_refresh(self): proj = Project(pk=123, name='test',order=0, doc_type=Project.Standard.code, \ description='refresh test', task_group='TGx', par_date=datetime.datetime.now()) proj.save() url = reverse('project.views.main_page',args=[])+'?refresh=1' self._check_page(url, status_code=302) self.failUnlessEqual(Project.objects.count(),1) self.failUnlessEqual(DenormalizedProject.backlog_poll().idle,False) poll_url = reverse('project.views.backlog_poll',args=[]) request = self.get_request(poll_url) poll = backlog_poll(request) status = json.loads(poll.content) self.failIfEqual(status['backlog'],0) self.failUnlessEqual(status['count'],0) self.wait_for_backlog_completion([DenormalizedProject], 10*Project.objects.count()) request = self.get_request(poll_url) poll = backlog_poll(request) status = json.loads(poll.content) self.failUnlessEqual(status['backlog'],0) self.failUnlessEqual(Project.objects.count(),1) self.failUnlessEqual(status['count'],Project.objects.count()) DenormalizedProject.objects.get(pk=proj.pk)
def useradd(request): if request.method=='POST': try: first_name = request.POST['first_name'].strip() last_name = request.POST['last_name'].strip() email = request.POST['email'].strip() password = request.POST['password'].strip() terms = request.POST['terms'].strip() print(first_name) print(last_name) print(email) print(password) print(type(terms), terms) except: return JsonResponse({'status':'ERROR', 'msg':'invalid data'}) if not first_name or not last_name or not email or not password or not terms: return JsonResponse({'status':'ERROR', 'msg':'incomplete data'}) if not validate_email(email): return JsonResponse({'status':'ERROR', 'msg':'invalid email'}) if terms != 'true': return JsonResponse({'status':'ERROR', 'msg':'terms not accepted'}) exits = User.objects.filter(email=email) if exits: return JsonResponse({'status':'ERROR', 'msg':'user already exist'}) #paso todos los filtros new_username = aux_keygen() user = User.objects.create_user(username=new_username, password=password, first_name=first_name, last_name=last_name, email=email) user.save() user=authenticate(username=new_username, password=password) p = Project(name="Initial Project") p.save() pu = ProjectUser(project=p, user=user, permission=0) pu.save() login(request, user) request.session['username']=user.username return JsonResponse({'status':'OK', 'msg':'added user'}) else: return JsonResponse({'status':'ERROR', 'msg':'invalid http method'})
def delete_participation(cls, scientist_id, data): """ :param scientist_id: :param data: {role_id, project_id} """ scientist = yield Scientist.get_by_id(scientist_id) project = yield Project.get_by_id(data[u'project_id']) scientist.participating_projects.remove(dict(project_id=project.id, role_id=data[u'role_id'])) yield scientist.save(fields=[u'participating_projects']) for i in xrange(len(project.participants)): if project.participants[i][u'id'] == data[u'role_id']: project.participants[i][u'status'] = globals.STATUS_DELETED yield project.save(fields=[u'participants'])
def delete_desired_project(cls, scientist_id, data): """ :param scientist_id: :param data: {project_id, vacancy_id} """ scientist = yield Scientist.get_by_id(scientist_id) project = yield Project.get_by_id(data[u'project_id']) scientist.desired_vacancies = [scientist.desired_vacancies[i] for i in xrange(len(scientist.desired_vacancies)) if scientist.desired_vacancies[i][u'vacancy_id'] != data[u'vacancy_id']] yield scientist.save(fields=[u'desired_vacancies']) project.responses = [project.responses[i] for i in xrange(len(project.responses)) if (project.responses[i][u'scientist_id'] != scientist_id) and (project.responses[u'vacancy_id'] != data[u'vacancy_id'])] yield project.save(fields=[u'responses'])
def add_response(cls, conn, data): """ Участник нажимает кнопку "Участвовать" у проекта. Добавляем втаблицу откликов новое значение. Прописываем отклик у ученого и у проекта. :param data: {scientist_id, project_id, vacancy_id, message} :type data: dict """ project = yield Project.get_by_id(data[u'project_id']) scientist = yield Scientist.get_by_id(data[u'scientist_id']) sql_query = get_insert_query(globals.TABLE_RESPONSES, data, returning=u'') try: yield momoko.Op(conn.execute, sql_query) except PSQLException, ex: logging.exception(ex) raise