def setUp(self): super().setUp() # Initial api auth application: self.initial_application_number = 1 # Create neccessary data self.applications_data = [ { 'name': "Batman application", 'description': "Bruce Wayne awesome application", 'active': True, }, { 'name': "Spiderman application", 'description': "Peter parker awesome application", 'active': False, }, ] self.applications = [] for i in self.applications_data: a = Application(name=i['name'], description=i['description'], active=i['active']) a.save() self.applications.append(a)
def test_application_permissions_relation(self): applications_data = [{ 'name': "Batman application", 'description': "Bruce Wayne awesome application", 'active': True, }, { 'name': "Spiderman application", 'description': "Peter parker awesome application", 'active': False, }, ] applications = [] for i in applications_data: a = Application(name=i['name'], description=i['description'], active=i['active']) a.save() applications.append(a) for i in self.permissions_data: p = ProjectPermission.objects.get(key=i['key']) url = reverse('api:projectpermission-detail', args=[p.id]) # Set the keys i['application_set'] = [x.id for x in applications] response = self.client.put(url, i) self.assertEqual(response.status_code, status.HTTP_200_OK) p.refresh_from_db() # Check self.assertEqual(len(applications_data), len(p.application_set.all()))
def test_application_permissions_relation(self): applications_data = [ { 'name': "Batman application", 'description': "Bruce Wayne awesome application", 'active': True, }, { 'name': "Spiderman application", 'description': "Peter parker awesome application", 'active': False, }, ] applications = [] for i in applications_data: a = Application(name=i['name'], description=i['description'], active=i['active']) a.save() applications.append(a) for i in self.permissions_data: p = ProjectPermission.objects.get(key=i['key']) url = reverse('api:projectpermission-detail', args=[p.id]) # Set the keys i['application_set'] = [x.id for x in applications] response = self.client.put(url, i) self.assertEqual(response.status_code, status.HTTP_200_OK) p.refresh_from_db() # Check self.assertEqual(len(applications_data), len(p.application_set.all()))
def test_saving_and_retrieving_applications(self): appList = AppList() appList.save() first_application = Application() first_application.company = 'The first (ever) application' first_application.app_list = appList first_application.save() second_application = Application() second_application.company = 'The second application' second_application.app_list = appList second_application.save() saved_app_list = AppList.objects.first() self.assertEqual(saved_app_list, appList) saved_applications = Application.objects.all() self.assertEqual(saved_applications.count(), 2) first_saved_application = saved_applications[0] second_saved_application = saved_applications[1] self.assertEqual(first_saved_application.company, 'The first (ever) application') self.assertEqual(first_saved_application.app_list, appList) self.assertEqual(second_saved_application.company, 'The second application') self.assertEqual(second_saved_application.app_list, appList)
def testApplicationCache(self): a = Application() a.name = "Test App" a.client_secret = "abc" a.id = "test-id" a.created_by = "Nick" a.save() application_cache().load_from_db() self.assertIn(a, application_cache().all())
def obj_create(self, bundle, **kwargs): """ Creates a new application """ try: user = User.objects.get(id=bundle.data['user_id']) print user company = Company.objects.get(id=bundle.data['company_id']) print company fair = Fair.objects.get(id=bundle.data['fair_id']) print fair if 'position' in bundle.data.keys(): position = bundle.data['position'] else: position = 'Any' if 'status' in bundle.data.keys(): status = bundle.data['status'] else: status = 1 # auto-checkin the user old_checkin = Hunt.objects.filter(user=user, fair=fair) if not len(old_checkin) > 0: new_checkin = Hunt(user=user, fair=fair) new_checkin.save() # check if an application already exists old_application = Application.objects.filter(user=user, company=company, fair=fair) if len(old_application) > 0: bundle.obj = old_application[0] else: new_application = Application(user=user, company=company, fair=fair, status=status, position=position) new_application.save() bundle.obj = new_application # update user preferences for Graduation Date, Major, Degree try: grad_year = bundle.data['grad_year'] user.student.graduation_year = grad_year user.student.save() except Exception, e: print e # raise e try: majors = bundle.data['majors'] for major in majors: major_obj = Major.objects.get(id=int(major)) user.student.major.add(major_obj) user.student.save() except Exception, e: print e
def setUp(self): self.client = Client() self.user_finder = MockUserFinder() self.user = self.user_finder.find(id=12) a = Application() a.id = uuid.uuid4().hex a.name = "Test Application" a.created_by = self.user['id'] a.client_secret = uuid.uuid4().hex a.redirect_uri = "http://example.com/redirect" a.save() self.application = a
def test_ap_is_authenticated(self): url = reverse('api:user-list') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # Create an api token so we could test a = Application(name="Test permissions") a.save() authorized_client = APIClient() authorized_client.credentials(HTTP_AUTHORIZATION='Bearer {0}'.format(a.token)) response = authorized_client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_ap_is_authenticated(self): url = reverse('api:user-list') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # Create an api token so we could test a = Application(name="Test permissions") a.save() authorized_client = APIClient() authorized_client.credentials( HTTP_AUTHORIZATION='Bearer {0}'.format(a.token)) response = authorized_client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK)
def obj_create(self, bundle, **kwargs): """ Creates a new application """ try: user = User.objects.get(id=bundle.data['user_id']) print user company = Company.objects.get(id=bundle.data['company_id']) print company fair = Fair.objects.get(id=bundle.data['fair_id']) print fair if 'position' in bundle.data.keys(): position = bundle.data['position'] else: position = 'Any' if 'status' in bundle.data.keys(): status = bundle.data['status'] else: status = 1 # auto-checkin the user old_checkin = Hunt.objects.filter(user=user, fair=fair) if not len(old_checkin) > 0: new_checkin = Hunt(user=user, fair=fair) new_checkin.save() # check if an application already exists old_application = Application.objects.filter(user=user, company=company, fair=fair) if len(old_application) > 0: bundle.obj = old_application[0] else: new_application = Application(user=user, company=company, fair=fair, status=status, position=position) new_application.save() bundle.obj = new_application # update user preferences for Graduation Date, Major, Degree try: grad_year = bundle.data['grad_year'] user.student.graduation_year = grad_year user.student.save() except Exception, e: print e # raise e try: majors = bundle.data['majors'] for major in majors: major_obj = Major.objects.get(id=int(major)) user.student.major.add(major_obj) user.student.save() except Exception, e: print e
def testInvalidateCacheView(self): a = Application() a.id = uuid.uuid4().hex a.client_secret = uuid.uuid4().hex a.super_application = True a.name = "Test Super App" a.redirect_uri = "/" a.created_by = "nick" a.save() sig = application_hasher(a, "secret") post_data = { 'uncache_type': 'user_request', 'user_id': 123 } resp = self.client.post("/cache/invalidate?client_id=%s&signature=%s&verify=%s" % (a.id, sig, "secret"), data=post_data) self.assertEqual('{"message": "OK"}', resp.content.decode())
def save(self, *args, **kwargs): if not self.pk: is_new = True else: is_new = False super(CustomAccount, self).save(*args, **kwargs) if is_new and self.category: application = Application() application.user = self application.category = self.category.applicationcategory application.save() for question in application.category.questions.all(): answer = ApplicationAnswer() answer.question = question answer.application = application answer.save()
def newApplication(request): if not isRecruiter(request.user): return render(request, 'error.html', { 'title': '403 - Forbidden', 'description': 'You are not a recruiter.' }) sample = string.lowercase + string.digits token = ''.join(random.sample(sample, 5)) app = Application(token=token) app.save() c = Comment(app=app, author=request.user.userprofile, date=datetime.utcnow(), text="Generated the Token", auto_generated=True) c.save() return HttpResponse( request.build_absolute_uri( reverse('applications:apply', kwargs={'token': token})))
def scanning_generate_view(request): if request.method == 'GET': credentials = [] count = int(request.GET.get('count', 1)) if count > 10: return JsonResponse( { 'status': 500, 'message': 'The count in this request is not included or too high. Max. 10' }, status=500) for x in range(count): user = User(email='tester' + str(randint(999, 9999999999)) + '@ugahacks.com', name='Tester Account') user.set_password('password1') user.save() application = Application(user=user, origin='test', first_timer=True, first_ugahacks=True, description="I'm a tester account", university="University of Georgia", degree="Computational Testing") application.save() credentials.append({ 'participantQr': application.uuid, 'badgeQr': uuid.uuid4() }) return JsonResponse({ 'status': 200, 'message': credentials, }, status=200)
def apply_anonymous(request): if not request.user.is_authenticated(): return redirect("core:register") try: app = request.user.userprofile.application if app.status != Application.OFFERED: return redirect("applications:mystatus") except ObjectDoesNotExist: sample = string.lowercase + string.digits token = ''.join(random.sample(sample, 5)) app = Application(token=token, applicantProfile=request.user.userprofile) app.save() c = Comment(app=app, author=request.user.userprofile, date=datetime.utcnow(), text="Started Application", auto_generated=True) c.save() return apply_common(request, app)
def setUp(self): super().setUp() # Initial api auth application: self.initial_application_number = 1 # Create neccessary data self.applications_data = [{ 'name': "Batman application", 'description': "Bruce Wayne awesome application", 'active': True, }, { 'name': "Spiderman application", 'description': "Peter parker awesome application", 'active': False, }, ] self.applications = [] for i in self.applications_data: a = Application(name=i['name'], description=i['description'], active=i['active']) a.save() self.applications.append(a)
def setUp(self): # Create an api token so we could test a = Application(name="Test wiggum") a.save() self.client.credentials( HTTP_AUTHORIZATION='Bearer {0}'.format(a.token))
def app_view(request): form = ApplicationForm(request.POST or None) print(form.errors) msg = None if request.method == "POST": if form.is_valid(): firstName = form.cleaned_data.get("firstname") lastName = form.cleaned_data.get("lastname") gender = form.cleaned_data.get("gender") employeeId = form.cleaned_data.get("employeeId") phone = form.cleaned_data.get("phone") doj = form.cleaned_data.get("doj") maritalstatus = form.cleaned_data.get("maritalstatus") physical = form.cleaned_data.get("physical") chronicillness = form.cleaned_data.get("chronicillness") email = form.cleaned_data.get("email") try: isApp = Application.objects.get(employee_id=employeeId) msg = "Application alredy created, plz try in Edit/Submit Application" form = ApplicationForm() except Application.DoesNotExist: app_ref = get_random_string().upper()[:8] user_ob = get_user_model()(username=app_ref) user_ob.set_password("app_" + app_ref) user_ob.save() points = 0 status = 'Pending' date_doj = datetime.strptime(doj, '%Y-%m-%d') expYrs = calculateExp(date_doj) if expYrs >= 8: points = 1 print('{} {}'.format(maritalstatus, gender)) if maritalstatus == '0' and gender == '2': points += 5 if physical == '1': points += 10 if chronicillness != '0': points += 1000 # This points is consider as the user can choose any location else: status = 'NotEligible' app = Application(app_ref_no=app_ref, first_name=firstName, last_name=lastName, gender=gender, employee_id=employeeId, phone_no=phone, date_of_join=doj, email=email, marital_status=maritalstatus, physical_disabled=physical, chronic_illness=chronicillness, created_by=user_ob, years_of_exp=expYrs, status=status, points=points) app.save() # sendAppMail(email, '{} {}'.format( # firstName, lastName), app_ref) msg = 'Application Submitted/Saved Successfully' # form = ApplicationForm() else: msg = 'Error validating the form' return render(request, "accounts/newapp.html", {"form": form, "msg": msg})
class ApplicationResourceTest(ResourceTestCase): #fixtures = ['test_applications.json'] def setUp(self): super(ApplicationResourceTest, self).setUp() self.api_list_url = '/api/v1/applications/' self.container_list_url = '/api/v1/containers/' self.username = '******' self.password = '******' self.user = User.objects.create_user(self.username, '*****@*****.**', self.password) self.api_key = self.user.api_key.key self.data = { 'name': 'test-app', 'description': 'test app', 'domain_name': 'test.example.com', 'backend_port': 1234, 'protocol': 'http' } host = Host() host.name = 'local' host.hostname = '127.0.0.1' host.save() self.host = host self.container_data = { 'image': 'base', 'command': '/bin/bash', 'description': 'test app', 'ports': [], 'hosts': ['/api/v1/hosts/1/'] } resp = self.api_client.post(self.container_list_url, format='json', data=self.container_data, authentication=self.get_credentials()) self.app = Application(**self.data) self.app.save() def tearDown(self): # clear apps Application.objects.all().delete() # remove all test containers for c in self.host.get_all_containers(): self.host.destroy_container(c.container_id) def get_credentials(self): return self.create_apikey(self.username, self.api_key) def test_get_list_unauthorzied(self): """ Test get without key returns unauthorized """ self.assertHttpUnauthorized(self.api_client.get(self.api_list_url, format='json')) def test_get_list_json(self): """ Test get application list """ resp = self.api_client.get(self.api_list_url, format='json', authentication=self.get_credentials()) self.assertValidJSONResponse(resp) def test_get_detail_json(self): """ Test get application details """ url = '{}1/'.format(self.api_list_url) resp = self.api_client.get(url, format='json', authentication=self.get_credentials()) self.assertValidJSONResponse(resp) data = self.deserialize(resp) keys = data.keys() self.assertTrue('name' in keys) self.assertTrue('description' in keys) self.assertTrue('domain_name' in keys) self.assertTrue('backend_port' in keys) self.assertTrue('containers' in keys) def test_create_application(self): """ Tests that applications can be created via api """ app_data = self.data app_data['domain_name'] = 'sample.example.com' resp = self.api_client.post(self.api_list_url, format='json', data=app_data, authentication=self.get_credentials()) self.assertHttpCreated(resp) resp = self.api_client.get(self.api_list_url, format='json', authentication=self.get_credentials()) self.assertValidJSONResponse(resp) data = self.deserialize(resp) d = data.get('objects')[-1] self.assertTrue(d.get('name') == app_data.get('name')) self.assertTrue(d.get('domain_name') == app_data.get('domain_name')) def test_update_application(self): """ Test update application """ url = '{}1/'.format(self.api_list_url) data = self.data app_name = 'app-updated' data['name'] = app_name resp = self.api_client.put(url, format='json', data=data, authentication=self.get_credentials()) self.assertHttpAccepted(resp) resp = self.api_client.get(url, format='json', authentication=self.get_credentials()) self.assertValidJSONResponse(resp) data = self.deserialize(resp) self.assertTrue(data.get('name') == app_name) def test_update_application_with_containers(self): """ Test update application with containers """ url = '{}1/'.format(self.api_list_url) container_url = '{}1/'.format(self.container_list_url) data = self.data data['containers'] = [container_url] resp = self.api_client.put(url, format='json', data=data, authentication=self.get_credentials()) self.assertHttpAccepted(resp) resp = self.api_client.get(url, format='json', authentication=self.get_credentials()) self.assertValidJSONResponse(resp) data = self.deserialize(resp) self.assertTrue(data.get('name') == self.data.get('name')) self.assertTrue(container_url in data.get('containers')) def test_delete_application(self): """ Test delete application """ url = '{}1/'.format(self.api_list_url) resp = self.api_client.delete(url, format='json', authentication=self.get_credentials()) self.assertHttpAccepted(resp) resp = self.api_client.get(url, format='json', authentication=self.get_credentials()) self.assertHttpNotFound(resp)
def app_view(request): form = ApplicationForm(request.POST or None) print(form.errors) msg = None smsg = None if request.method == "POST": if form.is_valid(): firstName = form.cleaned_data.get("firstname") lastName = form.cleaned_data.get("lastname") gender = form.cleaned_data.get("gender") employeeId = form.cleaned_data.get("employeeId") phone = form.cleaned_data.get("phone") doj = form.cleaned_data.get("doj") dob = form.cleaned_data.get("dob") maritalstatus = form.cleaned_data.get("maritalstatus") physical = form.cleaned_data.get("physical") chronicillness = form.cleaned_data.get("chronicillness") email = form.cleaned_data.get("email") school = form.cleaned_data.get("school") try: isApp = Application.objects.get(employee_id=employeeId) msg = "Employee alredy created." form = ApplicationForm() except Application.DoesNotExist: app_ref = get_random_string().upper()[:8] user_ob = get_user_model()(username=app_ref) user_ob.set_password("app_" + app_ref) user_ob.save() points = 0 status = 'Pending' expYrs = calculateExp(doj) try: sch = School.objects.get(id=school) schcategory = SchoolCategory.objects.get( id=sch.category_id) except School.DoesNotExist: sch = None except SchoolCategory.DoesNotExist: schcategory = None if schcategory: points = schcategory.point if expYrs >= 8: print('{} {}'.format(maritalstatus, gender)) if maritalstatus == '0' and gender == '2': points += 5 if physical == '1': points += 10 app = Application(app_ref_no=app_ref, first_name=firstName, last_name=lastName, gender=gender, employee_id=employeeId, phone_no=phone, date_of_join=doj, email=email, marital_status=maritalstatus, physical_disabled=physical, chronic_illness='0', created_by=user_ob, years_of_exp=expYrs, status=status, points=points, school=sch, date_of_birth=dob) app.save() sendAppMail(email, '{} {}'.format(firstName, lastName), app_ref) form = ApplicationForm() smsg = 'Employee saved successfully and sent email with ref no' else: msg = 'Employee is not eligible for transfer.' else: msg = 'Error validating the form' choices = getSchools() c = [] for choice in choices: c.append((choice.id, '{} - {}'.format(choice.school_name, choice.village))) form.fields['school'].widget.choices = c return render(request, "newapp.html", { "form": form, "msg": msg, 'segment': 'newapp', 'smsg': smsg })
def setUp(self): # Create an api token so we could test a = Application(name="Test wiggum") a.save() self.client.credentials( HTTP_AUTHORIZATION='Bearer {0}'.format(a.token))
print("partner_created", created) except: pass # seeding applications for _, row in df_student.iterrows(): # find corresponding Student try: student = Student.objects.get(email_address=row["Email Address"]) except ObjectDoesNotExist: continue choices = [] choices.append(row["1) What is your FIRST choice?"]) choices.append(row["2) What is your SECOND choice?"]) choices.append(row["3) What is your THIRD choice?"]) for i in range(3): # find corresponding Project try: project = Project.objects.get(project_name=choices[i]) application = Application( student=student, project=project, rank=i + 1, status="SUB", ) application.save() except ObjectDoesNotExist: continue
def apply(request, project_name): # this view shows the project name as well as the project questions # need to add user authentication # check to see if that partner project exists, if so, get the questions for it try: project = Project.objects.get(project_name=project_name) questions = Question.objects.filter( project=project) # .order_by('question_num') except Question.DoesNotExist: raise Http404("Question does not exist.") except Project.DoesNotExist: raise Http404("Project does not exist.") email = None if request.user.is_authenticated: email = request.user.email else: messages.info(request, "You must be logged in to apply to a project.") return redirect('/') try: student = Student.objects.get(email_address=email) except ObjectDoesNotExist: if Partner.objects.filter(email_address=email).count() > 0: messages.info(request, "You must be a student to apply to projects.") return redirect("/projects") else: messages.info( request, "You have not yet signed up. Please complete the signup form to continue." ) return redirect("/profile/signup") if not config.APPLICATIONS_OPEN: messages.info( request, "Applications are currently closed. If you believe you have received " "this message in error, please email [email protected].") return redirect("/projects") count = Application.objects.filter(student=student, created_at__range=[ config.APP_LIMIT_START_DATE, config.APP_LIMIT_END_DATE ]).count() if count > config.APP_LIMIT - 1 and not student.is_scholar: messages.info( request, f'You have already applied to {config.APP_LIMIT} projects.') return redirect('/projects') elif count > config.SCHOLAR_APP_LIMIT - 1 and student.is_scholar: messages.info( request, f'You have already applied to {config.SCHOLAR_APP_LIMIT} projects.' ) return redirect('/projects') count = Application.objects.filter(student=student, project=project).count() if count > 0: # raise Http404("Student already has an application submitted") messages.info(request, 'You have already applied to this project.') return redirect('/projects') # if this form is submitted, then we want to save the answers if request.method == 'POST': post = request.POST.copy() def querydict_to_dict(query_dict): data = {} for key in query_dict.keys(): v = query_dict.getlist(key) if len(v) == 1: v = v[0] data[key] = v return data is_valid = True question_ids = list(post.keys()) ans_list = [] # creating individual answers for q_id in question_ids: if q_id == "csrfmiddlewaretoken": continue if len(post[q_id].strip()) == 0: is_valid = False break new_ans = request.POST.copy() new_ans_keys = list(new_ans.keys()) q_num = 0 answer_text = "" for new_k in new_ans_keys: if new_k == "csrfmiddlewaretoken": continue if new_k == q_id: q_num = new_k # answer_text = post[new_k] asDict = querydict_to_dict(post) if type(asDict[q_id]) != list: answer_text = asDict[q_id] else: answer_text = ";".join(asDict[q_id]) new_ans.pop(new_k) new_ans['question'] = Question.objects.get(id=q_num) new_ans['answer_text'] = answer_text ans_list.append(new_ans) # print(ans_list) for skill in get_default_skills(): if (skill not in student.skills.keys()) or ( not student.skills[skill]): messages.info( request, 'Please ensure you have filled out your skill levels in your profile.' ) return redirect("/profile/") if is_valid: try: application = Application.objects.get(student=student, project=project) except: application = Application(student=student, project=project, status="SUB") application.save() answers = [] for post in ans_list: # print(post) request.POST = post form = AnswerForm(request.POST) if form.is_valid(): # print("Is valid") question = form.cleaned_data['question'] try: a = Answer.objects.get(student=student, application=application, question=question) a.answer_text = form.cleaned_data['answer_text'] except: a = Answer( student=student, application=application, question=question, answer_text=form.cleaned_data['answer_text']) a.save() answers.append(a) else: # cleanup on failure application.delete() for a in answers: a.delete() logger.error( f"Invalid answer for application {application}:\n{form}" ) messages.info( request, 'Your application was invalid and could not be processed. If this error persists, ' 'please contact [email protected].') return redirect('/projects') # TODO: allow students to update rank # studentUpdater = Student.objects.filter(email_address = email) # if not student.first_choice: # studentUpdater.update(first_choice = project.project_name) # elif not student.second_choice: # studentUpdater.update(second_choice = project.project_name) # elif not student.third_choice: # studentUpdater.update(third_choice = project.project_name) # else: # # raise Http404("Student has applied to 3 applications") # messages.info(request, 'You have already applied to 3 projects.') # return redirect('/projects') # application.save() send_app_confirmation_email(application) messages.info(request, 'Your application has been submitted successfully!') return redirect('/projects') else: messages.info( request, 'Your application was invalid and could not be processed. If this error persists, ' 'please contact [email protected].') return redirect(request.path_info) else: # GET form = AnswerForm() args = {} args.update(csrf(request)) args['form'] = form # print(project, type(project)) # print(questions) if request.user.is_authenticated: print(questions) return render(request, 'projects/application.html', { 'questions': questions, 'project': project, 'form': form }) else: raise PermissionDenied("User is not logged in.")