Best Python code snippet using django-test-plus_python
test_population_indicators.py
Source: test_population_indicators.py
...41 area_level3 = AreaLevelFactory()42 # disaggregate the population, but no areas in arealevel43 response = self.post('arealevels-intersect-areas', pk=area_level3.pk,44 data=data)45 self.assert_http_202_accepted(response)46 # ToDo: Note CF: testing for a specific message text???? that is strange47 self.assertEqual(response.data.get('message'), 'No areas available')48 # disaggregate the population and use precalculated rastercells49 # ToDo: shouldn't the populations have a reference to the area_level(s)?50 # workaround by getting the supposed area_level indirectly51 for area_level_id in self.popraster.rastercellpopulation_set.values_list(52 'area__area_level', flat=True).distinct():53 if area_level_id is None:54 continue55 response = self.post('arealevels-intersect-areas',56 pk=area_level_id,57 data={'drop_constraints': False,})58 self.assert_http_202_accepted(response)59 print(response.data.get('message'))60 # disaggregate the population and use precalculated rastercells61 response = self.post('populations-disaggregate', pk=population.pk,62 data={'use_intersected_data': True,63 'drop_constraints': False, })64 self.assert_http_202_accepted(response)65 print(response.data.get('message'))66 unknown_level = max(AreaLevel.objects.all().values_list('id', flat=True)) + 167 response = self.post('arealevels-intersect-areas',68 pk=unknown_level,69 data={'drop_constraints': False,})70 self.assert_http_406_not_acceptable(response)71 def test_disaggregate_population(self):72 """Test if the population is correctly Disaggregated to RasterCells"""73 population: Population = self.population74 # disaggregate the population75 response = self.post('populations-disaggregate', pk=-1,76 data={'drop_constraints': False, })77 self.assert_http_406_not_acceptable(response)78 # disaggregate the population79 response = self.post('populations-disaggregate', pk=population.pk,80 data={'drop_constraints': False, })81 self.assert_http_202_accepted(response)82 print(response.data.get('message'))83 # do again to check updates84 response = self.post('populations-disaggregate', pk=population.pk,85 data={'drop_constraints': False, })86 self.assert_http_202_accepted(response)87 # get disaggregated population88 response = self.get_check_200(url='populations-get-details',89 pk=population.pk)90 df = pd.DataFrame.from_records(response.data['rastercellpopulationagegender_set'])91 # compare to population entry92 popentries = PopulationEntry.objects.filter(population=population)93 df_popentries = pd.DataFrame.from_records(94 popentries.values('area', 'gender', 'age_group', 'value'))95 # check by gender96 expected = df_popentries[['gender', 'value']].groupby('gender').sum()97 actual = df[['gender', 'value']].groupby('gender').sum()98 pd.testing.assert_frame_equal(actual, expected)99 # check by age_group100 expected = df_popentries[['age_group', 'value']].groupby('age_group').sum()101 actual = df[['age_group', 'value']].groupby('age_group').sum()102 pd.testing.assert_frame_equal(actual, expected)103 # check by cell104 actual = df[['cell', 'value']].groupby('cell').sum()105 # disaggregate the population106 response = self.post('populations-disaggregateall',107 data={'drop_constraints': False, })108 self.assert_http_202_accepted(response)109 print(response.data.get('message'))110 def test_area_without_rasterpopulation(self):111 """112 Test what happens, if there is population in an area,113 but no rastercells with values to distribute114 """115 #delete the existing cellcodes in area3116 cellcodes_area3 = [f'100mN{n:05}E{e:05}'117 for n, e in118 [(30226, 42482), (30227, 42483)]]119 rcp = RasterCellPopulation.objects.filter(cell__cellcode__in=cellcodes_area3)120 rcp.delete()121 #add a population entries in area3122 area3 = AreaAttribute.objects.get(field__name='gen', str_value='area3').area123 age_group = AgeGroup.objects.first()124 gender = Gender.objects.first()125 PopulationEntry.objects.create(population=self.population,126 area=area3,127 age_group=age_group,128 gender=gender,129 value=444)130 gender = Gender.objects.last()131 PopulationEntry.objects.create(population=self.population,132 area=area3,133 age_group=age_group,134 gender=gender,135 value=555)136 # Disaggregate the population137 response = self.post('populations-disaggregate', pk=self.population.pk,138 data={'drop_constraints': False,})139 self.assert_http_202_accepted(response)140 # there should be a message about the not distributed inhabitants141 self.assertIn('999.0 Inhabitants not located to rastercells',142 response.data.get('message'))143 self.assertIn('area3', response.data.get('message'))144 # get disaggregated population145 response = self.get_check_200(url='populations-get-details',146 pk=self.population.pk)147 df = pd.DataFrame.from_records(response.data['rastercellpopulationagegender_set'])148 # compare to population entry149 popentries = PopulationEntry.objects.filter(population=self.population)150 df_popentries = pd.DataFrame.from_records(151 popentries.values('area', 'gender', 'age_group', 'value'))152 # check results by gender, ignore population in area3153 expected = df_popentries.loc[df_popentries.area != area3.id]\154 [['gender', 'value']]\155 .groupby('gender')\156 .sum()157 actual = df[['gender', 'value']].groupby('gender').sum()158 pd.testing.assert_frame_equal(actual, expected)159 # Delete area2+3 with its population160 aa2_and_3 = AreaAttribute.objects.filter(field__name='gen',161 str_value__in=['area2', 'area3'])162 area_2_and_3 = Area.objects.filter(id__in=aa2_and_3.values('area'))163 area_2_and_3.delete()164 # Disaggregate the population165 response = self.post('populations-disaggregate', pk=self.population.pk,166 data={'drop_constraints': False,})167 self.assert_http_202_accepted(response)168 # get disaggregated population169 response = self.get_check_200(url = 'populations-get-details',170 pk=self.population.pk)171 df = pd.DataFrame.from_records(response.data['rastercellpopulationagegender_set'])172 # compare to population entry173 popentries = PopulationEntry.objects.filter(population=self.population)174 df_popentries = pd.DataFrame.from_records(175 popentries.values('area', 'gender', 'age_group', 'value'))176 # check by gender177 expected = df_popentries[['gender', 'value']].groupby('gender').sum()178 actual = df[['gender', 'value']].groupby('gender').sum()179 pd.testing.assert_frame_equal(actual, expected)180 def aggregate_population(self):181 """aggregate populations to all arealevels"""...
test_templates_stops_traveltimes.py
...40 'excel_file' : file_content,41 }42 url = reverse('stops-upload-template')43 res = self.client.post(url, data, extra=dict(format='multipart/form-data'))44 self.assert_http_202_accepted(res, msg=res.content)45 # 4 stops should have been uploaded with the correct hst-nr and names46 df = pd.read_excel(file_path_stops, skiprows=[1])47 actual = pd.DataFrame(Stop.objects.values('id', 'name')).set_index('id')48 expected = df[['HstNr', 'HstName']]\49 .rename(columns={'HstNr': 'id','HstName': 'name',})\50 .set_index('id')51 pd.testing.assert_frame_equal(actual, expected)52 # assert that without edit_basedata-permissions no upload is possible53 self.profile.can_edit_basedata = False54 self.profile.save()55 res = self.client.post(url, data, extra=dict(format='multipart/form-data'))56 self.assert_http_403_forbidden(res)57 def test_upload_broken_stop_file(self):58 """59 test errors in upload files60 """61 file_path = os.path.join(os.path.dirname(__file__),62 self.testdata_folder,63 self.filename_stops_errors)64 url = reverse('stops-upload-template')65 data = {66 'excel_file' : open(file_path, 'rb'),67 'drop_constraints': False,68 }69 res = self.client.post(url, data, extra=dict(format='multipart/form-data'))70 self.assertContains(res,71 'Haltestellennummer ist nicht eindeutig',72 status_code=406)73 print(res.content)74 def create_mode_variant(self) -> int:75 return ModeVariantFactory().pk76 def upload_stops(self, filename_stops: str='Haltestellen.xlsx'):77 url = reverse('stops-upload-template')78 data = {79 'excel_file' : open(self.get_file_path_stops(filename_stops), 'rb'),80 'drop_constraints': False,81 }82 res = self.client.post(url, data, extra=dict(format='multipart/form-data'))83 self.assert_http_202_accepted(res, msg=res.content)84 def test_request_template_matrixstopstop(self):85 url = reverse('matrixstopstops-create-template')86 res = self.post(url)87 self.assert_http_200_ok(res)88 wb = load_workbook(BytesIO(res.content))89 self.assertListEqual(wb.sheetnames, ['Reisezeit'])90 def test_upload_matrixstopstop_template(self):91 """92 test bulk upload matrix93 """94 for fn_stops, fn_matrix in [95 ('Haltestellen.xlsx', 'Reisezeitmatrix_Haltestelle_zu_Haltestelle.xlsx'),96 ('Haltestellen_HL.xlsx', 'Reisezeimatrix_HL_klein.mtx')97 ]:98 self.upload_stops(fn_stops)99 mode_variant_id = self.create_mode_variant()100 file_path = os.path.join(os.path.dirname(__file__),101 self.testdata_folder,102 fn_matrix)103 file_content = open(file_path, 'rb')104 data = {105 'excel_or_visum_file' : file_content,106 'variant': mode_variant_id,107 'drop_constraints': False,108 }109 url = reverse('matrixstopstops-upload-template')110 res = self.client.post(url, data, extra=dict(format='multipart/form-data'))111 self.assert_http_202_accepted(res, msg=res.content)112 if fn_matrix.endswith('.xlsx'):113 df = pd.read_excel(file_path, skiprows=[1])114 elif fn_matrix.endswith('mtx'):115 da = ReadPTVMatrix(file_path)116 df = da['matrix'].to_dataframe()117 df = df.loc[df['matrix']<999999]118 df.index.rename(['from_stop', 'to_stop'], inplace=True)119 df.rename(columns={'matrix': 'minutes',}, inplace=True)120 df.reset_index(inplace=True)121 actual = pd.DataFrame(122 MatrixStopStop.objects.values('from_stop', 'to_stop', 'minutes'))\123 .set_index(['from_stop', 'to_stop'])124 expected = df[['from_stop', 'to_stop', 'minutes']].set_index(['from_stop', 'to_stop'])125 pd.testing.assert_frame_equal(actual, expected, check_dtype=False)...
test_matrixcreation.py
Source: test_matrixcreation.py
...30 'drop_constraints': False,31 'speed': 4,32 'max_distance': 500,}33 res = self.post('matrixcellplaces-precalculate-traveltime', data=data)34 self.assert_http_202_accepted(res)35 print(res.content)36 print(MatrixCellPlace.objects.filter(variant=walk.pk).count())37 data = {'variant': car.pk,38 'drop_constraints': False,39 'speed': 20,40 'max_distance': 5000,}41 res = self.post('matrixcellplaces-precalculate-traveltime', data=data)42 self.assert_http_202_accepted(res)43 print(res.content)44 print(MatrixCellPlace.objects.filter(variant=car.pk).count())45 data = {'variant': car.pk,46 'drop_constraints': False,47 'speed': 4,48 'max_distance': 5000,}49 res = self.post('matrixcellstops-precalculate-traveltime', data=data)50 self.assert_http_202_accepted(res)51 print(res.content)52 print(MatrixCellStop.objects.filter(variant=car.pk).count())53 data = {'variant': car.pk,54 'drop_constraints': False,55 'speed': 4,56 'max_distance': 5000,}57 res = self.post('matrixplacestops-precalculate-traveltime', data=data)58 self.assert_http_202_accepted(res)59 print(res.content)...
Check out the latest blogs from LambdaTest on this topic:
“Test frequently and early.” If you’ve been following my testing agenda, you’re probably sick of hearing me repeat that. However, it is making sense that if your tests detect an issue soon after it occurs, it will be easier to resolve. This is one of the guiding concepts that makes continuous integration such an effective method. I’ve encountered several teams who have a lot of automated tests but don’t use them as part of a continuous integration approach. There are frequently various reasons why the team believes these tests cannot be used with continuous integration. Perhaps the tests take too long to run, or they are not dependable enough to provide correct results on their own, necessitating human interpretation.
How do we acquire knowledge? This is one of the seemingly basic but critical questions you and your team members must ask and consider. We are experts; therefore, we understand why we study and what we should learn. However, many of us do not give enough thought to how we learn.
While there is a huge demand and need to run Selenium Test Automation, the experts always suggest not to automate every possible test. Exhaustive Testing is not possible, and Automating everything is not sustainable.
It’s strange to hear someone declare, “This can’t be tested.” In reply, I contend that everything can be tested. However, one must be pleased with the outcome of testing, which might include failure, financial loss, or personal injury. Could anything be tested when a claim is made with this understanding?
Agile project management is a great alternative to traditional methods, to address the customer’s needs and the delivery of business value from the beginning of the project. This blog describes the main benefits of Agile for both the customer and the business.
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!