def setUp(self): self.client = APIClient() self.email_1 = "*****@*****.**" self.author_name_1 = "João" self.full_name_1 = "João Maria" self.id_number_1 = "111111111" self.ist_1 = "S" self.phone_1 = "123456789" self.id_type = "CC" self.user_service = UserService() logged_in_user = CustomUser(email="*****@*****.**", password="******", author_name="aaa", full_name="aaaa", id_type=self.id_type, id_number="123", ist_student_options=self.ist_1, phone="1234", department="AD", role="DI") logged_in_user.save() token = RefreshToken.for_user(logged_in_user).access_token self.auth_headers = {'HTTP_AUTHORIZATION': 'Bearer ' + str(token)}
def setUp(self): self.client = APIClient() program_service = ProgramService() p1 = program_service.create_program(authors=list(get_user_model().objects.all()), name="P1", max_duration=57) p2 = program_service.create_program(authors=list(get_user_model().objects.all()), name="P2") p3 = program_service.create_program(authors=list(get_user_model().objects.all()), name="P3") slot_service = SlotService() midnight = datetime.strptime("00:03", "%H:%M") slot_service.create_slot(1, midnight, p1, False) slot_service.create_slot(2, midnight, p2, False) slot_service.create_slot(3, midnight, p3, False) logged_in_user = CustomUser(email="*****@*****.**", password="******", author_name="aaa", full_name="aaaa", id_type="CC", id_number="123", ist_student_options="Y", phone="1234", role="DI") logged_in_user.save() token = RefreshToken.for_user(logged_in_user).access_token self.auth_headers = { 'HTTP_AUTHORIZATION': 'Bearer ' + str(token) }
class DataSetUpToTests(BaseModelTestCase): model_class = Report required_input = { "date": datetime.datetime.now().date(), "description": "Some description", "author": None, "project": None, "work_hours": datetime.timedelta(hours=8), } def setUp(self): task_type = TaskActivityType(pk=1, name="Other") task_type.save() self.SAMPLE_STRING_FOR_TYPE_VALIDATION_TESTS = "This is a string" self.author = CustomUser(email="*****@*****.**", password="******", first_name="John", last_name="Doe") self.author.save() self.project = Project(name="Test Project", start_date=datetime.datetime.now()) self.project.save() self.required_input["author"] = self.author self.required_input["project"] = self.project self.REPORT_MODEL_DATA = self.required_input.copy()
def addAuthor(authorJSON): author = authorJSON try: author = CustomUser.objects.get(pk=author["id"].split("/")[-1]) return author except: # print(author["url"]) if "github" not in author: author["github"] = "" if "url" not in author: author["url"] = "" author = CustomUser(timestamp=timezone.now(), id=author["id"].split("/")[-1], username=author["id"].split("/")[-1], password="******", displayname=author["displayName"], host=author["host"], github_url=author["github"], url=author["url"]) author.save() return author
class BookingtModelTestCase(TestCase): """This class defines the test suite for the flights model.""" def setUp(self): """Define the test client and other test variables.""" self.user = CustomUser(username='******', email='*****@*****.**', password="******") self.user.save() self.airline = Airline(name="KLM", flight_number="A360") self.airline.save() self.flight = Flight(airline=self.airline, from_location='Jos', to_location='Lagos', departure_time='2019-06-14 02:33:00+01', arrival_time='2019-06-14 02:33:00+01', price=21000, no_of_seats=100) self.flight.save() def test_model_can_create_a_booking(self): """Test the flight model can create a flight.""" old_count = Booking.objects.count() Booking.objects.create(flight=self.flight, user=self.user) self.flight.save() new_count = Booking.objects.count() self.assertNotEqual(old_count, new_count)
class WebsiteTestCase(TestCase): def setUp(self): #Creating user instance self.user1 = CustomUser(username="******", email="*****@*****.**", password="******") self.user1.save() #Creating website details and saving self.website1 = Website(image='images/Tarmac.png', title="WebLandingPage", description="A cool website", url='www.awwwards.com', posted_by=self.user1) self.website1.save() def test_instance(self): self.assertTrue(isinstance(self.website1, Website)) def test_save_method(self): self.website1.save_website() websites = Website.objects.all() self.assertTrue(len(websites) > 0) def test_search_filter(self): self.website1.save() searched_websites = Website.search_by_title('WebLandingPage') self.assertTrue(len(searched_websites) == 1) def tearDown(self): Website.objects.all().delete()
def MealPlanDelete(request, pk): if request.method == 'POST': CurrentRecord = MealPlan.objects.get(id=pk) # Check we are the logged in user for security if request.user == CurrentRecord.User: # needs to be filter rather than get so that .exists() works a = CustomUser.objects.filter(username=settings.ARCHIVE_USERNAME) if not a.exists(): b = CustomUser(username=settings.ARCHIVE_USERNAME, email=settings.ARCHIVE_USER_EMAIL) b.save() #Change the record in Meal PLan to the archive user CurrentRecord.User = CustomUser.objects.get( username=settings.ARCHIVE_USERNAME) # Could also clear out comments e.g. CurrentRecord.PlanName= '' etc CurrentRecord.save() return HttpResponseRedirect('/MealPlanList') else: PlanName = MealPlan.objects.get(id=pk).friendlyname() context = {"MealPlanName": PlanName} return render(request, 'AppTimesCalc/mealplan_confirm_delete.html', context)
def test_cant_login_if_user_is_inactive(client): user = CustomUser(identifier='inactive_user', is_active=False) user.set_password('test') user.save() response = client.post(reverse('auth:login'), {'username': '******', 'password': '******'}) assert response.status_code == status.HTTP_403_FORBIDDEN assert 'inactive or deleted' in response.content.decode('utf-8')
def create(self, validated_data): username = validated_data.get("username") email = validated_data.get("email") password = validated_data.get("password") user = CustomUser(username=username, email=email, password=password) user.save() return user
def general_statistics(request): CustomUser.update_user_activity(user=request.user) users = CustomUser.objects.all() dirs_all = Directory.objects.using('directories').count() dirs_classified = Directory.objects.using('directories').exclude( classifications_amount=0).count() percent = dirs_classified / dirs_all * 100 return render(request, 'general-stat-log.html', locals())
def setUp(self): self.client = Client() user = CustomUser(first_name="Tester", last_name="1", email="*****@*****.**") user.save() community = Community(author=user, name="Test Community", created_on=datetime.datetime.now(), description="Hi Test") community.save() self.community = community
def auth_login(request): content = {} auth_token_id = request.GET['token'] auth_username = request.GET['username'] auth_login_url = "%s%s%s%s%s" % (auth_url, "/api/grouprole/?uid=", auth_username, app_key, app_name) headers = {'content-type': 'application/json'} auth_result = requests.get(auth_login_url, headers=headers) auth_data = auth_result.json() if len(auth_data["groups"]) > 0: content["Role"] = auth_data["groups"] memberurl = "%s%s%s%s%s" % (auth_url, "api/member/?uid=", auth_username, app_key, app_name) headers = {'content-type': 'application/json'} member_result = requests.get(memberurl, headers=headers, ) memberdata = member_result.json() if CustomUser.objects.filter(username=auth_username).count() == 0: try: data = CustomUser(username=auth_username, is_staff=1, first_name=memberdata["fullname"], email=memberdata["mail"], department=auth_data["groups"], mobile=memberdata["mobile"], user_key=memberdata["key"]) except KeyError: data = CustomUser(username=auth_username, is_staff=1, first_name=memberdata["fullname"], email=memberdata["mail"], department=auth_data["groups"], mobile=memberdata["mobile"], user_key="") data.save() user_list = CustomUser.objects.get(username=auth_username) user_list.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user_list) request.session.set_expiry(60 * 60 * 3) content.update(csrf(request)) return HttpResponseRedirect('/') else: salt_data = CustomUser.objects.get(username=auth_username) salt_data.first_name = memberdata["fullname"] salt_data.email = memberdata["mail"] salt_data.department = auth_data["groups"] salt_data.mobile = memberdata["mobile"] try: salt_data.user_key = memberdata["key"] except KeyError: salt_data.user_key = "" salt_data.save() salt_data.backend = 'django.contrib.auth.backends.ModelBackend' login(request, salt_data) session_id = hashlib.sha1(auth_token_id + auth_key + auth_username).hexdigest() user_list = CustomUser.objects.get(username=auth_username) request.session.set_expiry(60 * 60 * 3) content.update(csrf(request)) return HttpResponseRedirect('/') else: return render_to_response('default/error.html')
def setUp(self): user = CustomUser(email="*****@*****.**") user.save() self.user = user self.client = APIClient() self.client.force_authenticate(user=user) self.post_data = { 'title':'test title', 'author': user.id } self.response = self.client.post( reverse('create'), self.post_data, format='json')
def setUp(self): #Creating user instance self.user1 = CustomUser(username="******", email="*****@*****.**", password="******") self.user1.save() #Creating website details and saving self.website1 = Website(image='images/Tarmac.png', title="WebLandingPage", description="A cool website", url='www.awwwards.com', posted_by=self.user1) self.website1.save()
def get_queryset(self): """ Adding this method since it is sometimes called when using django-rest-swagger https://github.com/Tivix/django-rest-auth/issues/275 """ return CustomUser().objects.all()
def setUp(self): """ setup for testing logged in user """ self.user = CustomUser( first_name='UserA', email='*****@*****.**') self.user.save() self.second_user = CustomUser( first_name='UserB', email='*****@*****.**', parental_key='test-key' ) # self.second_user.save() # login self.client = Client() self.client.force_login(user=self.user)
def test_logout_with_login(self): user = CustomUser(username='******', email='*****@*****.**', password='******') client = Client() client.login(username='******', password = '******') response = client.get(reverse('users:logout')) self.assertEqual(response.status_code, 302) self.assertRedirects(response, reverse('myblog:index'))
class TestGardenInstance: """ Test that various properties are created by default on a new Garden object """ GARDEN_NAME = "Secret Garden" EMAIL = "*****@*****.**" PASSWORD = "******" user = CustomUser(email=EMAIL, password=PASSWORD) garden = Garden(name=GARDEN_NAME, owner=user) """ name is assigned to __str__ method """ def test_str_matches_garden_name(self): assert str(self.garden) == self.GARDEN_NAME """ name matches what we entered """ def test_garden_name_matches(self): assert self.name == self.GARDEN_NAME """ start_date exists as a date """ def test_start_date_property_exists_as_a_date(self): assert isinstance(self.garden.start_date, datetime) """ is_active property defaults to true """ def test_is_active_property_exists(self): assert self.garden.is_active == True """ owner refers to the user passed as argument """ def test_owner_is_passed_user(self): assert (self.garden.owner.email == self.EMAIL and self.garden.owner.password == self.PASSWORD)
def register(request): """if POST method, checks whether username or email are already in use by other accounts if GET method, renders register page. Returns: returns login page, if new user was created, reloads register page otherwise. """ if request.method == "GET": return render(request, 'register.html') if request.POST.get('check_username'): username = str(request.POST['check_username']) return JsonResponse({ 'name_available': not CustomUser.objects.filter(username=username)}) if request.POST.get('check_mail'): email = str(request.POST['check_mail']) return JsonResponse({'mail_available': not CustomUser.objects.filter(email=email)}) name = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') user = CustomUser.create(username=name, password=password, email=email) if user: user.is_active = True user.save() return redirect('login') return render(request, 'register.html', status=400)
def generate_attendance(self): # Device that collect data from student's cards and save at some server ENDPOINT_URL = 'https://some_device.com/api_v1/get_data' while True: data = self.request(ENDPOINT_URL).json() self.stdout.write( self.style.SUCCESS(f"Data recieved at {time.time()}.")) with open(f'../media/documents/attendance/{time.time()}.json', 'w') as f: json.load(data, f, indent=4, ensure_ascii=False) attendance_instance = Attendance.objects.create( title=f'Лист посещаемости от {date.today()}', document=f, date=datetime.now(), author=CustomUser.get(pk=0)) self.stdout.write( self.style.SUCCESS( f"Data saved at {time.time()}.\nLocation: {attendance_instance.document.url}.\nSleeping untill next call..." )) time.sleep(43200)
def setUp(self): self.test_product = { 'id': '123', 'nutrition_grades': "a", 'product_name': "product nametest", 'generic_name': "gen_name description", 'image_front_url': "URL IMAGE", 'image_nutrition_url': "url nutri", 'url': "url", 'categories_hierarchy': ['cat1', 'cat2', 'cat3'], } CustomUser(first_name='first name test', email='*****@*****.**', password='******').save() Product(id=self.test_product['id'], nutriscore=self.test_product['nutrition_grades'], name=self.test_product['product_name'], summation=self.test_product['generic_name'], picture=self.test_product['image_front_url'], nutrition=self.test_product['image_nutrition_url'], external_link=self.test_product['url']).save() self.client = Client()
def logout_user(request): logout(request) form = CustomUser(request.POST or None) context = { "form": form, } return redirect('index')
def test_that_project_report_list_should_return_list_of_all_reports_assigned_to_project(self): other_user = CustomUser( email="*****@*****.**", password="******", first_name="Jane", last_name="Doe", is_active=True, ) other_user.save() self.project.members.add(other_user) other_project = Project(name="Project test", start_date=datetime.datetime.now()) other_project.save() other_project.members.add(self.user) other_project.members.add(other_user) other_project_report = Report( date=datetime.datetime.now().date(), description="Some other description", author=self.user, project=other_project, work_hours=datetime.timedelta(hours=8), ) other_project_report.save() other_report_1 = Report( date=datetime.datetime.now().date(), description="Some other description", author=other_user, project=self.project, work_hours=datetime.timedelta(hours=8), ) other_report_1.save() other_report_2 = Report( date=datetime.date(2001, 1, 1), description="Some other description", author=self.user, project=self.project, work_hours=datetime.timedelta(hours=8), ) other_report_2.save() response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, ProjectReportList.template_name) self.assertContains(response, self.project.name) self._assert_response_contain_report(response, [self.report, other_report_1, other_report_2])
def setUp(self): self.factory = RequestFactory() self.Author = CustomUser(IDNumber=9608066506180, Role="Member", first_name="James", last_name="Watters") Paper.objects.create(Title="Test", Date=datetime.datetime.today()) Paper.objects.create(Title="Nopaper", Date=datetime.datetime.today())
def save_project_user(self, request, data): if request.user.is_authenticated: user = request.user else: try: user = CustomUser.objects.get(email=data['email'].lower()) except CustomUser.DoesNotExist: user = CustomUser(email=data['email'].lower(), username=self.generate_username(data['email'].lower()), accepted_terms_condition=True) user.set_password(data['password']) user.save() login(request, user) current_site = get_current_site(request) send_activation_email.delay(current_site.domain, model_to_dict(user)) else: if user.check_password(data['password']): login(request, user) else: return 0 project = Project(title=data['name_project'], description=data['descr_project'], type=str(data['trader'].id), loc=data['loc'], status=ProjectStatus.INACTIVE.value, user=user) project.save() return project.id
def setUp(self): task_type = TaskActivityType(pk=1, name="Other") task_type.save() self.SAMPLE_STRING_FOR_TYPE_VALIDATION_TESTS = "This is a string" self.author = CustomUser(email="*****@*****.**", password="******", first_name="John", last_name="Doe") self.author.save() self.project = Project(name="Test Project", start_date=datetime.datetime.now()) self.project.save() self.required_input["author"] = self.author self.required_input["project"] = self.project self.REPORT_MODEL_DATA = self.required_input.copy()
def generate_xlsx_for_single_user(self, author: CustomUser) -> Workbook: reports = author.get_reports_created().order_by( "date", "project__name") # type: ReportQuerySet self._workbook = Workbook() self._set_xlsx_settings_for_user_report() employee_name = get_employee_name(author) self._fill_report_for_single_user(employee_name, reports) self._set_printing_settings_for_current_sheet() return self._workbook
def userRegistration(request): if request.method=='POST': user_name=request.POST['user_name'] first_name=request.POST['first_name'] last_name=request.POST['last_name'] address1=request.POST['address1'] address2=request.POST['address2'] city=request.POST['city'] email=request.POST['email_address'] password1=request.POST['password1'] password2=request.POST['password2'] print request.POST print first_name if password1==password2: #Creating a auth_user instance new_user=User() new_user.first_name=first_name new_user.last_name=last_name new_user.username=user_name current_time=datetime.datetime.now() print current_time new_user.date_joined=current_time new_user.is_active=True new_user.is_superuser=False new_user.is_staff=False new_user.set_password(password1) new_user.email=email print new_user new_user.save() #Creating a users_customusers instance customuser=CustomUser() user_id=User.objects.get(username=user_name) print user_id customuser.addressLine1=address1 customuser.addressLine2=address2 customuser.city=city customuser.totalPurchase=0.0 customuser.user_id=user_id.id customuser.save() return HttpResponseRedirect(reverse('shop.views.home')) else: error_message="Password doesn't match"
def data(): user = CustomUser(identifier='test') user.set_password('test') user.save() return {'username': '******', 'password': '******'}