From 5508072f567e1978189e27eef32b04e75d498e8a Mon Sep 17 00:00:00 2001 From: Guillaume Englert Date: Mon, 24 Apr 2023 10:41:53 +0200 Subject: [PATCH] New test method 'get_alone_element()'. --- creme/activities/tests/test_activity.py | 21 +- creme/activities/tests/test_calendar.py | 28 +- creme/activities/tests/test_mass_import.py | 15 +- creme/assistants/tests/test_alert.py | 19 +- creme/assistants/tests/test_todo.py | 20 +- creme/assistants/tests/test_user_message.py | 29 +- creme/billing/tests/base.py | 6 +- creme/billing/tests/test_convert.py | 30 +- creme/billing/tests/test_credit_note.py | 4 +- creme/billing/tests/test_export.py | 20 +- creme/billing/tests/test_invoice.py | 33 +- creme/billing/tests/test_line.py | 4 +- .../billing/tests/test_payment_information.py | 10 +- creme/billing/tests/test_quote.py | 24 +- creme/billing/tests/test_sales_order.py | 3 +- creme/commercial/tests/test_act.py | 15 +- .../tests/test_act_objective_pattern.py | 20 +- .../tests/test_commercial_approach.py | 13 +- creme/commercial/tests/test_strategy.py | 25 +- creme/creme_config/tests/test_bricks.py | 71 +- creme/creme_config/tests/test_custom_field.py | 5 +- creme/creme_config/tests/test_custom_form.py | 5 +- .../creme_config/tests/test_entity_filter.py | 10 +- .../creme_config/tests/test_generics_views.py | 5 +- creme/creme_config/tests/test_menu.py | 25 +- creme/creme_config/tests/test_registry.py | 9 +- .../creme_config/tests/test_relation_type.py | 5 +- creme/creme_config/tests/test_search.py | 12 +- creme/creme_config/tests/test_user.py | 15 +- creme/creme_config/tests/test_user_role.py | 111 +--- .../tests/transfer/test_exporting.py | 32 +- .../tests/transfer/test_importing.py | 106 +-- creme/creme_core/tests/base.py | 9 + .../creme_core/tests/core/test_entity_cell.py | 6 +- creme/creme_core/tests/core/test_paginator.py | 5 +- .../tests/forms/test_entity_cell.py | 5 +- .../tests/forms/test_entity_filter.py | 605 ++++++++---------- creme/creme_core/tests/forms/test_fields.py | 10 +- creme/creme_core/tests/forms/test_listview.py | 40 +- creme/creme_core/tests/gui/test_actions.py | 24 +- creme/creme_core/tests/gui/test_bricks.py | 73 +-- .../creme_core/tests/gui/test_custom_form.py | 39 +- creme/creme_core/tests/gui/test_menu.py | 16 +- creme/creme_core/tests/gui/test_misc.py | 20 +- creme/creme_core/tests/models/test_bricks.py | 49 +- .../tests/models/test_entity_filter.py | 45 +- .../creme_core/tests/models/test_file_ref.py | 10 +- creme/creme_core/tests/models/test_history.py | 12 +- creme/creme_core/tests/models/test_search.py | 33 +- .../tests/models/test_setting_value.py | 20 +- creme/creme_core/tests/test_backends.py | 5 +- creme/creme_core/tests/test_base_test_case.py | 34 + .../creme_core/tests/utils/test_chunktools.py | 5 +- creme/creme_core/tests/utils/test_meta.py | 6 +- .../creme_core/tests/utils/test_xls_utils.py | 9 +- .../tests/views/entity/test_bulk_update.py | 9 +- .../tests/views/entity/test_deletion.py | 10 +- creme/creme_core/tests/views/test_auth.py | 5 +- .../tests/views/test_batch_process.py | 5 +- creme/creme_core/tests/views/test_bricks.py | 13 +- .../tests/views/test_creme_property.py | 6 +- .../tests/views/test_entity_filter.py | 32 +- .../creme_core/tests/views/test_enumerable.py | 10 +- creme/creme_core/tests/views/test_generic.py | 10 +- .../tests/views/test_header_filter.py | 5 +- creme/creme_core/tests/views/test_imprint.py | 10 +- .../tests/views/test_mass_export.py | 22 +- .../tests/views/test_mass_import.py | 82 +-- creme/creme_core/tests/views/test_merge.py | 29 +- creme/creme_core/tests/views/test_relation.py | 5 +- creme/crudity/tests/test_inputs.py | 82 +-- creme/crudity/tests/test_views.py | 15 +- creme/cti/tests.py | 24 +- creme/documents/tests/test_document.py | 29 +- creme/documents/tests/test_folder.py | 10 +- .../emails/tests/synchronization/test_job.py | 172 ++--- .../tests/synchronization/test_views.py | 10 +- creme/emails/tests/test_mail.py | 29 +- creme/emails/tests/test_sending.py | 7 +- creme/emails/tests/test_utils.py | 5 +- creme/geolocation/tests/test_populate.py | 10 +- creme/geolocation/tests/test_views.py | 27 +- creme/opportunities/tests/test_billing.py | 19 +- creme/opportunities/tests/test_mass_import.py | 5 +- creme/persons/tests/contact/test_main.py | 7 +- .../persons/tests/contact/test_mass_import.py | 5 +- creme/persons/tests/organisation/test_main.py | 10 +- .../persons/tests/organisation/test_merge.py | 5 +- creme/persons/tests/test_address.py | 15 +- creme/persons/tests/test_bricks.py | 5 +- creme/persons/tests/test_buttons.py | 15 +- creme/polls/tests/test_forms.py | 7 +- creme/polls/tests/test_poll_form.py | 30 +- creme/polls/tests/test_poll_reply.py | 6 +- creme/products/tests/test_product.py | 5 +- creme/products/tests/test_service.py | 5 +- creme/projects/tests.py | 49 +- creme/recurrents/tests/test_ticket.py | 10 +- .../tests/core/graph/test_aggregator.py | 32 +- .../tests/core/graph/test_cell_constraint.py | 22 +- creme/reports/tests/test_bricks.py | 21 +- creme/reports/tests/test_graph.py | 7 +- creme/reports/tests/test_report.py | 7 +- creme/sms/tests/test_sending.py | 5 +- creme/tickets/tests.py | 8 +- creme/vcfs/tests/test_app.py | 7 +- creme/vcfs/tests/test_import.py | 6 +- 107 files changed, 1000 insertions(+), 1816 deletions(-) diff --git a/creme/activities/tests/test_activity.py b/creme/activities/tests/test_activity.py index c9f0243dd8..9592cc6318 100644 --- a/creme/activities/tests/test_activity.py +++ b/creme/activities/tests/test_activity.py @@ -1385,10 +1385,9 @@ def test_createview_related01(self): self.assertEqual(2, Relation.objects.count()) - relations = Relation.objects.filter(type=constants.REL_SUB_PART_2_ACTIVITY) - self.assertEqual(1, len(relations)) - - relation = relations[0] + relation = self.get_alone_element( + Relation.objects.filter(type=constants.REL_SUB_PART_2_ACTIVITY) + ) self.assertEqual(contact02.id, relation.subject_entity_id) self.assertEqual(meeting.id, relation.object_entity_id) @@ -1586,9 +1585,10 @@ def test_editview01(self): self.assertEqual(type_id, activity.type.id) self.assertEqual(sub_type_id, activity.sub_type.id) - relations = Relation.objects.filter(type=constants.REL_SUB_PART_2_ACTIVITY) - self.assertEqual(1, len(relations)) - self.assertEqual(rel, relations[0]) + part_rel = self.get_alone_element( + Relation.objects.filter(type=constants.REL_SUB_PART_2_ACTIVITY) + ) + self.assertEqual(rel, part_rel) def test_editview02(self): "Change type." @@ -2195,14 +2195,11 @@ def test_listviews(self): def test_listview_bulk_actions(self): user = self.login() - export_actions = [ + export_action = self.get_alone_element( action for action in actions.actions_registry.bulk_actions(user=user, model=Activity) if isinstance(action, BulkExportICalAction) - ] - self.assertEqual(1, len(export_actions)) - - export_action = export_actions[0] + ) self.assertEqual('activities-export-ical', export_action.type) self.assertEqual(reverse('activities__dl_ical'), export_action.url) self.assertIsNone(export_action.action_data) diff --git a/creme/activities/tests/test_calendar.py b/creme/activities/tests/test_calendar.py index 82f0d3e40c..049826d62b 100644 --- a/creme/activities/tests/test_calendar.py +++ b/creme/activities/tests/test_calendar.py @@ -525,10 +525,7 @@ def test_add_user_calendar01(self): }, )) - cals = Calendar.objects.filter(user=user) - self.assertEqual(1, len(cals)) - - cal = cals[0] + cal = self.get_alone_element(Calendar.objects.filter(user=user)) self.assertEqual(name, cal.name) self.assertEqual(color, cal.color) self.assertIs(cal.is_default, True) @@ -1181,9 +1178,9 @@ def test_activities_data_multiple_users_public_default(self): @override_settings(ACTIVITIES_DEFAULT_CALENDAR_IS_PUBLIC=False) def test_selected_calendars_in_session(self): user = self.login() - sessions_before = self._get_user_sessions(user) - self.assertEqual(1, len(sessions_before)) - self.assertNotIn('activities__calendars', sessions_before[0]) + + session_before = self.get_alone_element(self._get_user_sessions(user)) + self.assertNotIn('activities__calendars', session_before) other_user = self.other_user @@ -1216,19 +1213,19 @@ def test_selected_calendars_in_session(self): Calendar.objects.filter(id__in=get_ctxt('others_selected_calendar_ids')), ) - sessions_after = self._get_user_sessions(user) - self.assertEqual(1, len(sessions_after)) + session_after = self.get_alone_element(self._get_user_sessions(user)) self.assertCountEqual( [cal1.id, cal3.id], - sessions_after[0]['activities__calendars'], + session_after['activities__calendars'], ) @override_settings(ACTIVITIES_DEFAULT_CALENDAR_IS_PUBLIC=True) def test_calendars_select(self): user = self.login() - sessions1 = self._get_user_sessions(user) - self.assertEqual(1, len(sessions1)) - self.assertNotIn('activities__calendars', sessions1[0]) + # sessions1 = self._get_user_sessions(user) + # self.assertEqual(1, len(sessions1)) + session1 = self.get_alone_element(self._get_user_sessions(user)) + self.assertNotIn('activities__calendars', session1[0]) other_user = self.other_user @@ -1243,11 +1240,10 @@ def test_calendars_select(self): self.assertGET405(url) self.assertPOST200(url, data={'add': [str(cal1.id), str(cal2.id)]}) - sessions2 = self._get_user_sessions(user) - self.assertEqual(1, len(sessions2)) + session2 = self.get_alone_element(self._get_user_sessions(user)) self.assertCountEqual( [cal1.id, cal2.id], - sessions2[0]['activities__calendars'], + session2['activities__calendars'], ) # Ignore other not-public Calendars diff --git a/creme/activities/tests/test_mass_import.py b/creme/activities/tests/test_mass_import.py index 9e7b3eebac..68f93b18f9 100644 --- a/creme/activities/tests/test_mass_import.py +++ b/creme/activities/tests/test_mass_import.py @@ -207,10 +207,7 @@ def test_import01(self): ) self.assertEqual(constants.NARROW, act7.floating_type) - jr_errors = [r for r in results if r.messages] - self.assertEqual(1, len(jr_errors)) - - jr_error = jr_errors[0] + jr_error = self.get_alone_element(r for r in results if r.messages) self.assertListEqual( [_('End time is before start time')], jr_error.messages, @@ -356,10 +353,7 @@ def test_import02(self): results = self._get_job_results(job) self.assertEqual(len(lines), len(results)) - jr_errors = [r for r in results if r.messages] - self.assertEqual(1, len(jr_errors)) - - jr_error = jr_errors[0] + jr_error = self.get_alone_element(r for r in results if r.messages) self.assertEqual( [_('The participant «{}» cannot be found').format(unfoundable)], jr_error.messages, @@ -468,10 +462,7 @@ def test_import03(self): results = self._get_job_results(job) self.assertEqual(len(lines), len(results)) - jr_errors = [r for r in results if r.messages] - self.assertEqual(1, len(jr_errors)) - - jr_error = jr_errors[0] + jr_error = self.get_alone_element(r for r in results if r.messages) err_fmt = _('The participant «{}» cannot be found').format self.assertListEqual( [ diff --git a/creme/assistants/tests/test_alert.py b/creme/assistants/tests/test_alert.py index 25e1348571..32acd81710 100644 --- a/creme/assistants/tests/test_alert.py +++ b/creme/assistants/tests/test_alert.py @@ -409,9 +409,8 @@ def test_create_with_absolute_date(self): self.assertEqual(title, str(alert)) - jobs = queue.refreshed_jobs - self.assertEqual(1, len(jobs)) - self.assertEqual(self.get_reminder_job(), jobs[0][0]) + job, _data = self.get_alone_element(queue.refreshed_jobs) + self.assertEqual(self.get_reminder_job(), job) def test_create_with_relative_datetime(self): "DatetimeField + dynamic user." @@ -926,20 +925,15 @@ def test_reminder1(self): self.assertLess(job.type.next_wakeup(job, now_value), now()) self.execute_reminder_job(job) - reminders = DateReminder.objects.exclude(id__in=reminder_ids) - self.assertEqual(1, len(reminders)) - reminder = reminders[0] + reminder = self.get_alone_element(DateReminder.objects.exclude(id__in=reminder_ids)) self.assertEqual(alert1, reminder.object_of_reminder) self.assertEqual(1, reminder.ident) self.assertDatetimesAlmostEqual(now_value, reminder.date_of_remind, seconds=60) self.assertTrue(self.refresh(alert1).reminded) self.assertFalse(self.refresh(alert2).reminded) - messages = mail.outbox - self.assertEqual(1, len(messages)) - - message = messages[0] + message = self.get_alone_element(mail.outbox) self.assertEqual([user.email], message.to) software = 'My CRM' @@ -994,9 +988,8 @@ def test_reminder3(self): self.execute_reminder_job(self.get_reminder_job()) self.assertEqual(1, DateReminder.objects.exclude(id__in=reminder_ids).count()) - messages = mail.outbox - self.assertEqual(1, len(messages)) - self.assertEqual([self.other_user.email], messages[0].to) + message = self.get_alone_element(mail.outbox) + self.assertEqual([self.other_user.email], message.to) @override_settings(DEFAULT_TIME_ALERT_REMIND=30) def test_next_wakeup1(self): diff --git a/creme/assistants/tests/test_todo.py b/creme/assistants/tests/test_todo.py index 36999110da..5fb8997181 100644 --- a/creme/assistants/tests/test_todo.py +++ b/creme/assistants/tests/test_todo.py @@ -528,20 +528,14 @@ def test_reminder01(self): self.execute_reminder_job(job) self.assertIsNone(job.user) - reminders = DateReminder.objects.all() - self.assertEqual(1, len(reminders)) - - reminder = reminders[0] + reminder = self.get_alone_element(DateReminder.objects.all()) self.assertEqual(todo1, reminder.object_of_reminder) self.assertEqual(1, reminder.ident) self.assertDatetimesAlmostEqual(now_value, reminder.date_of_remind, seconds=60) self.assertTrue(self.refresh(todo1).reminded) self.assertFalse(self.refresh(todo4).reminded) - messages = mail.outbox - self.assertEqual(1, len(messages)) - - message = messages[0] + message = self.get_alone_element(mail.outbox) self.assertEqual([user.email], message.to) software = 'My CRM' @@ -621,10 +615,7 @@ def send_messages(this, messages): self.assertTrue(send_messages_called) self.assertEqual(1, DateReminder.objects.exclude(id__in=reminder_ids).count()) - jresults = JobResult.objects.filter(job=job) - self.assertEqual(1, len(jresults)) - - jresult = jresults[0] + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ _( @@ -688,9 +679,8 @@ def test_reminder05(self): self.execute_reminder_job(self.get_reminder_job()) self.assertEqual(1, DateReminder.objects.count()) - messages = mail.outbox - self.assertEqual(1, len(messages)) - self.assertEqual([self.other_user.email], messages[0].to) + message = self.get_alone_element(mail.outbox) + self.assertEqual([self.other_user.email], message.to) def test_next_wakeup01(self): "Next wake is one day later + minimum hour." diff --git a/creme/assistants/tests/test_user_message.py b/creme/assistants/tests/test_user_message.py index 2ac28eeb00..4d73411f72 100644 --- a/creme/assistants/tests/test_user_message.py +++ b/creme/assistants/tests/test_user_message.py @@ -92,10 +92,7 @@ def test_create01(self): ) self._create_usermessage(title, body, priority, [user01], entity) - messages = UserMessage.objects.all() - self.assertEqual(1, len(messages)) - - message = messages[0] + message = self.get_alone_element(UserMessage.objects.all()) self.assertEqual(title, message.title) self.assertEqual(body, message.body) self.assertEqual(priority, message.priority) @@ -112,9 +109,8 @@ def test_create01(self): self.assertEqual(title, str(message)) - jobs = queue.refreshed_jobs - self.assertEqual(1, len(jobs)) - self.assertEqual(self._get_usermessages_job(), jobs[0][0]) + job, _data = self.get_alone_element(queue.refreshed_jobs) + self.assertEqual(self._get_usermessages_job(), job) @override_settings(SOFTWARE_LABEL='My CRM') def test_create02(self): @@ -183,10 +179,7 @@ def test_create03(self): self._create_usermessage('TITLE', 'BODY', priority, [user01], None) - messages = UserMessage.objects.all() - self.assertEqual(1, len(messages)) - - message = messages[0] + message = self.get_alone_element(UserMessage.objects.all()) self.assertIsNone(message.entity_id) self.assertIsNone(message.entity_content_type_id) # self.assertIsNone(message.creme_entity) @@ -372,9 +365,7 @@ def test_delete_priority01(self): def test_delete_priority02(self): priority = UserMessagePriority.objects.create(title='Important') self._create_usermessage('TITLE', 'BODY', priority, [self.user], None) - - messages = UserMessage.objects.all() - self.assertEqual(1, len(messages)) + self.get_alone_element(UserMessage.objects.all()) response = self.assertPOST200(reverse( 'creme_config__delete_instance', @@ -410,14 +401,10 @@ def send_messages(this, messages): self.assertTrue(self.send_messages_called) - messages = UserMessage.objects.all() - self.assertEqual(1, len(messages)) - self.assertTrue(messages[0].email_sent) - - jresults = JobResult.objects.filter(job=job) - self.assertEqual(1, len(jresults)) + message = self.get_alone_element(UserMessage.objects.all()) + self.assertTrue(message.email_sent) - jresult = jresults[0] + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ _('An error occurred while sending emails'), diff --git a/creme/billing/tests/base.py b/creme/billing/tests/base.py index 9b79465f53..95fb3bf09d 100644 --- a/creme/billing/tests/base.py +++ b/creme/billing/tests/base.py @@ -703,10 +703,10 @@ def assertConvertButtons(self, response, expected): else: self.assertEqual('span', button_node.tag) self.assertIn('forbidden', button_node.attrib.get('class').split()) - labels = [*filter(None, (txt.strip() for txt in button_node.itertext()))] - self.assertEqual(1, len(labels)) found.append({ - 'label': labels[0], + 'label': self.get_alone_element( + filter(None, (txt.strip() for txt in button_node.itertext())) + ), # 'json_data': json_data, 'disabled': True, }) diff --git a/creme/billing/tests/test_convert.py b/creme/billing/tests/test_convert.py index 0b7d36725e..055e80f679 100644 --- a/creme/billing/tests/test_convert.py +++ b/creme/billing/tests/test_convert.py @@ -137,10 +137,7 @@ def test_with_address(self): self.assertFalse(Invoice.objects.count()) self._convert(200, quote, 'invoice') - invoices = Invoice.objects.all() - self.assertEqual(1, len(invoices)) - - invoice = invoices[0] + invoice = self.get_alone_element(Invoice.objects.all()) self.assertEqual( _('{src} (converted into {dest._meta.verbose_name})').format( src=quote.name, dest=Invoice, @@ -206,9 +203,8 @@ def test_disabled_rtype(self): rtype.enabled = True rtype.save() - invoices = Invoice.objects.all() - self.assertEqual(1, len(invoices)) - self.assertRelationCount(0, invoices[0], REL_SUB_INVOICE_FROM_QUOTE, quote) + invoice = self.get_alone_element(Invoice.objects.all()) + self.assertRelationCount(0, invoice, REL_SUB_INVOICE_FROM_QUOTE, quote) @skipIfCustomQuote @skipIfCustomSalesOrder @@ -239,10 +235,7 @@ def test_not_super_user(self): self._convert(200, quote, 'sales_order') self.assertEqual(0, Invoice.objects.count()) - orders = SalesOrder.objects.all() - self.assertEqual(1, len(orders)) - - order = orders[0] + order = self.get_alone_element(SalesOrder.objects.all()) self.assertEqual('ORD1', order.number) self.assertRelationCount(0, order, REL_SUB_INVOICE_FROM_QUOTE, quote) @@ -381,10 +374,7 @@ def test_with_lines(self): self._convert(200, quote, 'invoice') - invoices = Invoice.objects.all() - self.assertEqual(1, len(invoices)) - - invoice = invoices[0] + invoice = self.get_alone_element(Invoice.objects.all()) self.assertEqual(2, invoice.get_lines(ServiceLine).count()) self.assertEqual(2, invoice.get_lines(ProductLine).count()) @@ -433,9 +423,8 @@ def test_status01(self): self._convert(200, quote, 'sales_order') - orders = SalesOrder.objects.all() - self.assertEqual(1, len(orders)) - self.assertEqual(1, orders[0].status_id) + order = self.get_alone_element(SalesOrder.objects.all()) + self.assertEqual(1, order.status_id) @skipIfCustomQuote @skipIfCustomInvoice @@ -455,9 +444,8 @@ def test_status02(self): self._convert(200, quote, 'invoice') - invoices = Invoice.objects.all() - self.assertEqual(1, len(invoices)) - self.assertEqual(1, invoices[0].status_id) + invoice = self.get_alone_element(Invoice.objects.all()) + self.assertEqual(1, invoice.status_id) @skipIfCustomQuote def test_not_copiable_relations(self): diff --git a/creme/billing/tests/test_credit_note.py b/creme/billing/tests/test_credit_note.py index b727910312..f44ab0a204 100644 --- a/creme/billing/tests/test_credit_note.py +++ b/creme/billing/tests/test_credit_note.py @@ -825,9 +825,7 @@ def test_brick(self): self.get_brick_table_column_titles(brick_node2), ) rows = self.get_brick_table_rows(brick_node2) - self.assertEqual(1, len(rows)) - - table_cells = rows[0].findall('.//td') + table_cells = self.get_alone_element(rows).findall('.//td') self.assertEqual(4, len(table_cells)) self.assertInstanceLink(table_cells[0], entity=credit_note) diff --git a/creme/billing/tests/test_export.py b/creme/billing/tests/test_export.py index ccc7244691..0c1257e3ab 100644 --- a/creme/billing/tests/test_export.py +++ b/creme/billing/tests/test_export.py @@ -871,10 +871,7 @@ def test_export_invoice_latex(self): response = self.assertGET200(self._build_export_url(invoice), follow=True) self.assertEqual('application/pdf', response['Content-Type']) - filerefs = FileRef.objects.exclude(id__in=existing_fileref_ids) - self.assertEqual(1, len(filerefs)) - - fileref = filerefs[0] + fileref = self.get_alone_element(FileRef.objects.exclude(id__in=existing_fileref_ids)) self.assertTrue(fileref.temporary) self.assertEqual(f"{_('Invoice')}_{invoice.id}.pdf", fileref.basename) self.assertEqual(user, fileref.user) @@ -919,10 +916,7 @@ def test_export_invoice_weasyprint(self): response = self.assertGET200(self._build_export_url(invoice), follow=True) self.assertEqual('application/pdf', response['Content-Type']) - filerefs = FileRef.objects.exclude(id__in=existing_fileref_ids) - self.assertEqual(1, len(filerefs)) - - fileref = filerefs[0] + fileref = self.get_alone_element(FileRef.objects.exclude(id__in=existing_fileref_ids)) self.assertTrue(fileref.temporary) self.assertEqual('{}_{}.pdf'.format(_('Invoice'), invoice.id), fileref.basename) self.assertEqual(user, fileref.user) @@ -1094,10 +1088,7 @@ def test_export_invoice_xls01(self): response = self.assertGET200(self._build_export_url(invoice), follow=True) self.assertEqual('application/vnd.ms-excel', response['Content-Type']) - filerefs = FileRef.objects.exclude(id__in=existing_fileref_ids) - self.assertEqual(1, len(filerefs)) - - fileref = filerefs[0] + fileref = self.get_alone_element(FileRef.objects.exclude(id__in=existing_fileref_ids)) self.assertTrue(fileref.temporary) self.assertEqual(f"{_('Invoice')}_{invoice.id}.xls", fileref.basename) self.assertEqual(user, fileref.user) @@ -1353,9 +1344,8 @@ def test_export_quote_xls(self): response = self.assertGET200(self._build_export_url(quote), follow=True) self.assertEqual('application/vnd.ms-excel', response['Content-Type']) - filerefs = FileRef.objects.exclude(id__in=existing_fileref_ids) - self.assertEqual(1, len(filerefs)) - self.assertEqual(f"{_('Quote')}_{quote.id}.xls", filerefs[0].basename) + fileref = self.get_alone_element(FileRef.objects.exclude(id__in=existing_fileref_ids)) + self.assertEqual(f"{_('Quote')}_{quote.id}.xls", fileref.basename) lines = iter(XlrdReader(None, file_contents=b''.join(response.streaming_content))) diff --git a/creme/billing/tests/test_invoice.py b/creme/billing/tests/test_invoice.py index b80e2bfa8e..33f9e5721f 100644 --- a/creme/billing/tests/test_invoice.py +++ b/creme/billing/tests/test_invoice.py @@ -633,15 +633,12 @@ def test_listview_export_actions(self): user = self.login() invoice = self.create_invoice_n_orgas('Invoice #1')[0] - export_actions = [ + export_action = self.get_alone_element( action for action in actions.actions_registry .instance_actions(user=user, instance=invoice) if isinstance(action, ExportInvoiceAction) - ] - self.assertEqual(1, len(export_actions)) - - export_action = export_actions[0] + ) self.assertEqual('billing-export_invoice', export_action.id) self.assertEqual('redirect', export_action.type) self.assertEqual( @@ -655,15 +652,12 @@ def test_listview_generate_number_actions(self): user = self.login() invoice = self.create_invoice_n_orgas('Invoice #1')[0] - number_actions = [ + number_action = self.get_alone_element( action for action in actions.actions_registry .instance_actions(user=user, instance=invoice) if isinstance(action, GenerateNumberAction) - ] - self.assertEqual(1, len(number_actions)) - - number_action = number_actions[0] + ) self.assertEqual('billing-generate_number', number_action.id) self.assertEqual('billing-invoice-number', number_action.type) self.assertEqual( @@ -686,15 +680,12 @@ def test_listview_generate_number_actions_disabled(self): invoice.number = 'J03' invoice.save() - number_actions = [ + number_action = self.get_alone_element( action for action in actions.actions_registry .instance_actions(user=user, instance=invoice) if isinstance(action, GenerateNumberAction) - ] - self.assertEqual(1, len(number_actions)) - - number_action = number_actions[0] + ) self.assertEqual('billing-generate_number', number_action.id) self.assertEqual('billing-invoice-number', number_action.type) self.assertEqual( @@ -1439,9 +1430,7 @@ def test_brick01(self): self.get_brick_table_column_titles(brick_node2), ) rows = self.get_brick_table_rows(brick_node2) - self.assertEqual(1, len(rows)) - - table_cells = rows[0].findall('.//td') + table_cells = self.get_alone_element(rows).findall('.//td') self.assertEqual(5, len(table_cells)) self.assertInstanceLink(table_cells[0], entity=invoice) self.assertEqual(invoice.number, table_cells[1].text) @@ -1481,8 +1470,8 @@ def test_brick02(self): self.get_brick_table_column_titles(brick_node), ) rows = self.get_brick_table_rows(brick_node) - self.assertEqual(1, len(rows)) - self.assertEqual(4, len(rows[0].findall('.//td'))) + row = self.get_alone_element(rows) + self.assertEqual(4, len(row.findall('.//td'))) @override_settings(HIDDEN_VALUE='?') def test_brick03(self): @@ -1515,9 +1504,7 @@ def test_brick03(self): brick=bricks.ReceivedInvoicesBrick, ) rows = self.get_brick_table_rows(brick_node) - self.assertEqual(1, len(rows)) - - table_cells = rows[0].findall('.//td') + table_cells = self.get_alone_element(rows).findall('.//td') self.assertEqual(5, len(table_cells)) self.assertEqual('?', table_cells[0].text) self.assertEqual('?', table_cells[1].text) diff --git a/creme/billing/tests/test_line.py b/creme/billing/tests/test_line.py index 6db246097a..3e061495d1 100644 --- a/creme/billing/tests/test_line.py +++ b/creme/billing/tests/test_line.py @@ -990,10 +990,8 @@ def test_multi_save_lines02(self): }, ) self.assertNoFormError(response) - product_lines = ProductLine.objects.all() - self.assertEqual(1, len(product_lines)) - product_line = product_lines[0] + product_line = self.get_alone_element(ProductLine.objects.all()) self.assertEqual(name, product_line.on_the_fly_item) self.assertEqual(Decimal(unit_price), product_line.unit_price) self.assertEqual(Decimal(quantity), product_line.quantity) diff --git a/creme/billing/tests/test_payment_information.py b/creme/billing/tests/test_payment_information.py index ddb4c96ece..83fead4703 100644 --- a/creme/billing/tests/test_payment_information.py +++ b/creme/billing/tests/test_payment_information.py @@ -51,10 +51,7 @@ def test_createview01(self): }, )) - all_pi = PaymentInformation.objects.all() - self.assertEqual(1, len(all_pi)) - - pi = all_pi[0] + pi = self.get_alone_element(PaymentInformation.objects.all()) self.assertIs(True, pi.is_default) self.assertEqual(organisation, pi.organisation) self.assertEqual('', pi.bank_code) @@ -161,10 +158,7 @@ def test_related_createview01(self): }, )) - all_pi = PaymentInformation.objects.filter(organisation=source.id) - self.assertEqual(1, len(all_pi)) - - pi = all_pi[0] + pi = self.get_alone_element(PaymentInformation.objects.filter(organisation=source.id)) self.assertIs(True, pi.is_default) self.assertEqual(pi, self.refresh(invoice).payment_info) diff --git a/creme/billing/tests/test_quote.py b/creme/billing/tests/test_quote.py index e3fa2dcd61..4923e3313c 100644 --- a/creme/billing/tests/test_quote.py +++ b/creme/billing/tests/test_quote.py @@ -128,10 +128,7 @@ def test_createview01(self): "Source is not managed + no number given." self.login() - managed_orgas = [*Organisation.objects.filter_managed_by_creme()] - self.assertEqual(1, len(managed_orgas)) - - managed_orga = managed_orgas[0] + managed_orga = self.get_alone_element(Organisation.objects.filter_managed_by_creme()) response1 = self.assertGET200(reverse('billing__create_quote')) with self.assertNoException(): @@ -552,15 +549,12 @@ def test_listview_actions(self): user = self.login() quote = self.create_quote_n_orgas('Quote #1')[0] - export_actions = [ + export_action = self.get_alone_element( action for action in actions.actions_registry .instance_actions(user=user, instance=quote) if isinstance(action, ExportQuoteAction) - ] - self.assertEqual(1, len(export_actions)) - - export_action = export_actions[0] + ) self.assertEqual('billing-export_quote', export_action.id) self.assertEqual('redirect', export_action.type) self.assertEqual(reverse('billing__export', args=(quote.id,)), export_action.url) @@ -812,9 +806,7 @@ def test_brick01(self): self.get_brick_table_column_titles(brick_node2), ) rows = self.get_brick_table_rows(brick_node2) - self.assertEqual(1, len(rows)) - - table_cells = rows[0].findall('.//td') + table_cells = self.get_alone_element(rows).findall('.//td') self.assertEqual(4, len(table_cells)) self.assertInstanceLink(table_cells[0], entity=quote) self.assertEqual( @@ -853,8 +845,8 @@ def test_brick02(self): self.get_brick_table_column_titles(brick_node), ) rows = self.get_brick_table_rows(brick_node) - self.assertEqual(1, len(rows)) - self.assertEqual(3, len(rows[0].findall('.//td'))) + row = self.get_alone_element(rows) + self.assertEqual(3, len(row.findall('.//td'))) @override_settings(HIDDEN_VALUE='?') def test_brick03(self): @@ -887,9 +879,9 @@ def test_brick03(self): brick=ReceivedQuotesBrick, ) rows = self.get_brick_table_rows(brick_node) - self.assertEqual(1, len(rows)) + row = self.get_alone_element(rows) - table_cells = rows[0].findall('.//td') + table_cells = row.findall('.//td') self.assertEqual(4, len(table_cells)) self.assertEqual('?', table_cells[0].text) self.assertEqual('?', table_cells[1].text) diff --git a/creme/billing/tests/test_sales_order.py b/creme/billing/tests/test_sales_order.py index d5fbfe02e7..d33e432e9a 100644 --- a/creme/billing/tests/test_sales_order.py +++ b/creme/billing/tests/test_sales_order.py @@ -388,8 +388,7 @@ def test_brick(self): self.get_brick_table_column_titles(brick_node2), ) rows = self.get_brick_table_rows(brick_node2) - self.assertEqual(1, len(rows)) - table_cells = rows[0].findall('.//td') + table_cells = self.get_alone_element(rows).findall('.//td') self.assertEqual(4, len(table_cells)) self.assertInstanceLink(table_cells[0], entity=order) diff --git a/creme/commercial/tests/test_act.py b/creme/commercial/tests/test_act.py index 86dcd5ffa6..c7f6ff3195 100644 --- a/creme/commercial/tests/test_act.py +++ b/creme/commercial/tests/test_act.py @@ -95,10 +95,7 @@ def test_create01(self): ) self.assertNoFormError(response) - acts = Act.objects.all() - self.assertEqual(1, len(acts)) - - act = acts[0] + act = self.get_alone_element(Act.objects.all()) self.assertEqual(name, act.name) self.assertEqual(atype, act.act_type) self.assertEqual(date(year=2011, month=11, day=20), act.start) @@ -456,10 +453,7 @@ def test_add_objective01(self): }, )) - objectives = ActObjective.objects.filter(act=act) - self.assertEqual(1, len(objectives)) - - objective = objectives[0] + objective = self.get_alone_element(ActObjective.objects.filter(act=act)) self.assertEqual(name, objective.name) self.assertEqual(act, objective.act) self.assertEqual(0, objective.counter) @@ -576,9 +570,8 @@ def test_add_objectives_from_pattern01(self): # --- self.assertNoFormError(self.client.post(url, data={'pattern': pattern.id})) - objectives = ActObjective.objects.filter(act=act) - self.assertEqual(1, len(objectives)) - self.assertEqual(5, objectives[0].counter_goal) + objective = self.get_alone_element(ActObjective.objects.filter(act=act)) + self.assertEqual(5, objective.counter_goal) @skipIfCustomPattern def test_add_objectives_from_pattern02(self): diff --git a/creme/commercial/tests/test_act_objective_pattern.py b/creme/commercial/tests/test_act_objective_pattern.py index 05fd21cab0..73dba1650a 100644 --- a/creme/commercial/tests/test_act_objective_pattern.py +++ b/creme/commercial/tests/test_act_objective_pattern.py @@ -49,10 +49,7 @@ def test_create(self): ) self.assertNoFormError(response) - patterns = ActObjectivePattern.objects.all() - self.assertEqual(1, len(patterns)) - - pattern = patterns[0] + pattern = self.get_alone_element(ActObjectivePattern.objects.all()) self.assertEqual(name, pattern.name) self.assertEqual(average_sales, pattern.average_sales) self.assertEqual(segment, pattern.segment) @@ -137,10 +134,7 @@ def test_add_root_pattern_component01(self): }, )) - components = pattern.components.all() - self.assertEqual(1, len(components)) - - component = components[0] + component = self.get_alone_element(pattern.components.all()) self.assertEqual(name, component.name) self.assertIsNone(component.parent) self.assertIsNone(component.ctype) @@ -170,10 +164,7 @@ def test_add_root_pattern_component02(self): ) self.assertNoFormError(response) - components = pattern.components.all() - self.assertEqual(1, len(components)) - - component = components[0] + component = self.get_alone_element(pattern.components.all()) self.assertEqual(name, component.name) self.assertEqual(ct, component.ctype) self.assertIsNone(component.filter) @@ -233,10 +224,7 @@ def test_add_child_pattern_component01(self): }, )) - children = comp01.children.all() - self.assertEqual(1, len(children)) - - comp02 = children[0] + comp02 = self.get_alone_element(comp01.children.all()) self.assertEqual(name, comp02.name) self.assertEqual(comp01, comp02.parent) self.assertIsNone(comp02.ctype) diff --git a/creme/commercial/tests/test_commercial_approach.py b/creme/commercial/tests/test_commercial_approach.py index 6dd2063ee6..57592cce18 100644 --- a/creme/commercial/tests/test_commercial_approach.py +++ b/creme/commercial/tests/test_commercial_approach.py @@ -92,10 +92,7 @@ def test_createview(self): response = self.client.post(url, data={'title': title, 'description': description}) self.assertNoFormError(response) - commapps = CommercialApproach.objects.all() - self.assertEqual(1, len(commapps)) - - commapp = commapps[0] + commapp = self.get_alone_element(CommercialApproach.objects.all()) self.assertEqual(title, commapp.title) self.assertEqual(description, commapp.description) self.assertEqual(entity.id, commapp.entity_id) @@ -464,9 +461,8 @@ def test_job01(self): self._send_mails() messages = mail.outbox - self.assertEqual(1, len(messages)) - message = messages[0] + message = self.get_alone_element(messages) self.assertEqual( _('[{software}] The organisation «{organisation}» seems neglected').format( software='My CRM', organisation=customer, @@ -617,12 +613,11 @@ def send_messages(this, messages): job = self._send_mails() self.assertFalse(mail.outbox) - jresults = JobResult.objects.filter(job=job) - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ _('An error has occurred while sending emails'), _('Original error: {}').format(err_msg), ], - jresults[0].messages, + jresult.messages, ) diff --git a/creme/commercial/tests/test_strategy.py b/creme/commercial/tests/test_strategy.py index 50ec12a1c3..b58458d5e1 100644 --- a/creme/commercial/tests/test_strategy.py +++ b/creme/commercial/tests/test_strategy.py @@ -50,10 +50,7 @@ def test_strategy_create(self): ) self.assertNoFormError(response) - strategies = Strategy.objects.all() - self.assertEqual(1, len(strategies)) - - strategy = strategies[0] + strategy = self.get_alone_element(Strategy.objects.all()) self.assertEqual(name, strategy.name) self.assertRedirects(response, strategy.get_absolute_url()) @@ -114,10 +111,7 @@ def test_segment_add(self): }, )) - segment_info = strategy.segment_info.all() - self.assertEqual(1, len(segment_info)) - - description = segment_info[0] + description = self.get_alone_element(strategy.segment_info.all()) self.assertEqual(name, description.segment.name) self.assertEqual(product, description.product) self.assertEqual(place, description.place) @@ -233,10 +227,7 @@ def test_segment_link(self): ) self.assertNoFormError(response) - seginfo = strategy02.segment_info.all() - self.assertEqual(1, len(seginfo)) - - description = seginfo[0] + description = self.get_alone_element(strategy02.segment_info.all()) self.assertEqual(industry, description.segment) self.assertEqual(product, description.product) self.assertEqual(place, description.place) @@ -274,10 +265,7 @@ def test_segment_edit01(self): ) self.assertNoFormError(response) - descriptions = strategy.segment_info.all() - self.assertEqual(1, len(descriptions)) - - description = descriptions[0] + description = self.get_alone_element(strategy.segment_info.all()) self.assertEqual(name, description.segment.name) self.assertEqual(product, description.product) self.assertEqual(place, description.place) @@ -318,10 +306,7 @@ def test_segment_edit03(self): ) self.assertNoFormError(response) - seginfo = strategy.segment_info.all() - self.assertEqual(1, len(seginfo)) - - segment_desc = seginfo[0] + segment_desc = self.get_alone_element(strategy.segment_info.all()) self.assertEqual(segment, segment_desc.segment) self.assertFalse(segment_desc.product) diff --git a/creme/creme_config/tests/test_bricks.py b/creme/creme_config/tests/test_bricks.py index a0c333ffd7..db789c6b27 100644 --- a/creme/creme_config/tests/test_bricks.py +++ b/creme/creme_config/tests/test_bricks.py @@ -346,33 +346,27 @@ def test_add_detailview(self, superuser): def filter_locs(zone): return [bl for bl in b_locs if bl.zone == zone] - locations = filter_locs(BrickDetailviewLocation.TOP) - self.assertEqual(2, len(locations)) - # self.assertEqual(1, self._find_location(brick_top1.id_, locations).order) - # self.assertEqual(2, self._find_location(brick_top2.id_, locations).order) - self.assertEqual(1, self._find_location(brick_top1.id, locations).order) - self.assertEqual(2, self._find_location(brick_top2.id, locations).order) + top_locations = filter_locs(BrickDetailviewLocation.TOP) + self.assertEqual(2, len(top_locations)) + self.assertEqual(1, self._find_location(brick_top1.id, top_locations).order) + self.assertEqual(2, self._find_location(brick_top2.id, top_locations).order) - locations = filter_locs(BrickDetailviewLocation.LEFT) - self.assertEqual(2, len(locations)) - # self.assertEqual(1, self._find_location(brick_left1.id_, locations).order) - # self.assertEqual(2, self._find_location(brick_left2.id_, locations).order) - self.assertEqual(1, self._find_location(brick_left1.id, locations).order) - self.assertEqual(2, self._find_location(brick_left2.id, locations).order) + left_locations = filter_locs(BrickDetailviewLocation.LEFT) + self.assertEqual(2, len(left_locations)) + self.assertEqual(1, self._find_location(brick_left1.id, left_locations).order) + self.assertEqual(2, self._find_location(brick_left2.id, left_locations).order) - locations = filter_locs(BrickDetailviewLocation.RIGHT) - self.assertEqual(1, len(locations)) - # self.assertEqual(1, self._find_location(brick_right.id_, locations).order) - self.assertEqual(1, self._find_location(brick_right.id, locations).order) + right_locations = filter_locs(BrickDetailviewLocation.RIGHT) + self.assertEqual(1, len(right_locations)) + self.assertEqual(1, self._find_location(brick_right.id, right_locations).order) - locations = filter_locs(BrickDetailviewLocation.BOTTOM) - self.assertEqual(1, len(locations)) - # self.assertEqual(1, self._find_location(brick_bottom.id_, locations).order) - self.assertEqual(1, self._find_location(brick_bottom.id, locations).order) + bottom_locations = filter_locs(BrickDetailviewLocation.BOTTOM) + self.assertEqual(1, len(bottom_locations)) + self.assertEqual(1, self._find_location(brick_bottom.id, bottom_locations).order) self.assertListEqual( [''], - [loc.brick_id for loc in filter_locs(BrickDetailviewLocation.HAT)] + [loc.brick_id for loc in filter_locs(BrickDetailviewLocation.HAT)], ) def test_add_detailview_ignore_used_roles(self): @@ -583,27 +577,27 @@ def _aux_test_edit_detailview(self, role=None, superuser=False, def filter_locs(zone): return [bl for bl in b_locs if bl.zone == zone] - locations = filter_locs(BrickDetailviewLocation.TOP) - self.assertEqual(2, len(locations)) - self.assertEqual(1, self._find_location(brick_top1.id, locations).order) - self.assertEqual(2, self._find_location(brick_top2.id, locations).order) + top_locations = filter_locs(BrickDetailviewLocation.TOP) + self.assertEqual(2, len(top_locations)) + self.assertEqual(1, self._find_location(brick_top1.id, top_locations).order) + self.assertEqual(2, self._find_location(brick_top2.id, top_locations).order) - locations = filter_locs(BrickDetailviewLocation.LEFT) - self.assertEqual(2, len(locations)) - self.assertEqual(1, self._find_location(brick_left1.id, locations).order) - self.assertEqual(2, self._find_location(brick_left2.id, locations).order) + left_locations = filter_locs(BrickDetailviewLocation.LEFT) + self.assertEqual(2, len(left_locations)) + self.assertEqual(1, self._find_location(brick_left1.id, left_locations).order) + self.assertEqual(2, self._find_location(brick_left2.id, left_locations).order) - locations = filter_locs(BrickDetailviewLocation.RIGHT) - self.assertEqual(1, len(locations)) - self.assertEqual(1, self._find_location(brick_right.id, locations).order) + right_locations = filter_locs(BrickDetailviewLocation.RIGHT) + self.assertEqual(1, len(right_locations)) + self.assertEqual(1, self._find_location(brick_right.id, right_locations).order) - locations = filter_locs(BrickDetailviewLocation.BOTTOM) - self.assertEqual(1, len(locations)) - self.assertEqual(1, self._find_location(brick_bottom.id, locations).order) + bottom_locations = filter_locs(BrickDetailviewLocation.BOTTOM) + self.assertEqual(1, len(bottom_locations)) + self.assertEqual(1, self._find_location(brick_bottom.id, bottom_locations).order) self.assertListEqual( [''], - [loc.brick_id for loc in filter_locs(BrickDetailviewLocation.HAT)] + [loc.brick_id for loc in filter_locs(BrickDetailviewLocation.HAT)], ) def test_edit_detailview01(self): @@ -1657,10 +1651,7 @@ def test_add_relationbrick(self): # --- self.assertNoFormError(self.client.post(url, data={'relation_type': rt.id})) - rb_items = RelationBrickItem.objects.all() - self.assertEqual(1, len(rb_items)) - - rb_item = rb_items[0] + rb_item = self.get_alone_element(RelationBrickItem.objects.all()) self.assertEqual(rt.id, rb_item.relation_type.id) self.assertIsNone(rb_item.get_cells(ContentType.objects.get_for_model(FakeContact))) diff --git a/creme/creme_config/tests/test_custom_field.py b/creme/creme_config/tests/test_custom_field.py index 7de768ede7..bef39d053b 100644 --- a/creme/creme_config/tests/test_custom_field.py +++ b/creme/creme_config/tests/test_custom_field.py @@ -160,10 +160,7 @@ def test_add_ct01(self): }, )) - cfields = CustomField.objects.filter(content_type=ct) - self.assertEqual(1, len(cfields)) - - cfield = cfields[0] + cfield = self.get_alone_element(CustomField.objects.filter(content_type=ct)) self.assertEqual(name, cfield.name) self.assertEqual(field_type, cfield.field_type) self.assertIs(cfield.is_required, False) diff --git a/creme/creme_config/tests/test_custom_form.py b/creme/creme_config/tests/test_custom_form.py index e15e31d2fe..75fcfefe68 100644 --- a/creme/creme_config/tests/test_custom_form.py +++ b/creme/creme_config/tests/test_custom_form.py @@ -1853,10 +1853,7 @@ def get_ct_wrapper(model): orga_wrapper = get_ct_wrapper(FakeOrganisation) self.assertTrue(orga_wrapper.collapsed) - orga_descriptors = orga_wrapper.descriptors - self.assertEqual(1, len(orga_descriptors)) - - orga_creation_descriptor = orga_descriptors[0] + orga_creation_descriptor = self.get_alone_element(orga_wrapper.descriptors) self.assertIsList(orga_creation_descriptor.items, length=1) orga_item = orga_creation_descriptor.items[0] diff --git a/creme/creme_config/tests/test_entity_filter.py b/creme/creme_config/tests/test_entity_filter.py index b1fb8a09ad..8cbaf49f0a 100644 --- a/creme/creme_config/tests/test_entity_filter.py +++ b/creme/creme_config/tests/test_entity_filter.py @@ -126,10 +126,7 @@ def test_create01(self): self.assertIsNone(efilter.user) self.assertFalse(efilter.use_or) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(field_name, condition.name) self.assertDictEqual( @@ -204,10 +201,7 @@ def test_edit01(self): self.assertIs(efilter.is_custom, True) self.assertIsNone(efilter.user) - conditions = efilter.conditions.order_by('id') - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.order_by('id')) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(field_name, condition.name) self.assertDictEqual( diff --git a/creme/creme_config/tests/test_generics_views.py b/creme/creme_config/tests/test_generics_views.py index 717ca9acfc..1d81d6f797 100644 --- a/creme/creme_config/tests/test_generics_views.py +++ b/creme/creme_config/tests/test_generics_views.py @@ -858,10 +858,7 @@ def test_delete09(self): self.assertNoFormError(response) dcom = self.get_deletion_command_or_fail(FakeTicketPriority) - replacers = dcom.replacers - self.assertEqual(1, len(replacers)) - - replacer = replacers[0] + replacer = self.get_alone_element(dcom.replacers) self.assertEqual('SET', replacer.type_id) self.assertEqual(FakeTicket, replacer.model_field.model) self.assertEqual('priority', replacer.model_field.name) diff --git a/creme/creme_config/tests/test_menu.py b/creme/creme_config/tests/test_menu.py index 2ac58bcac6..cc985900ae 100644 --- a/creme/creme_config/tests/test_menu.py +++ b/creme/creme_config/tests/test_menu.py @@ -818,10 +818,7 @@ def test_add_special_level0_entry01(self): response2 = self.client.post(url, data={'entry_id': entry_id}) self.assertNoFormError(response2) - items = [*MenuConfigItem.objects.all()] - self.assertEqual(1, len(items)) - - special_item = items[0] + special_item = self.get_alone_element(MenuConfigItem.objects.all()) self.assertEqual('creme_core-creme', special_item.entry_id) self.assertEqual(0, special_item.order) self.assertDictEqual({}, special_item.entry_data) @@ -865,14 +862,10 @@ def test_add_special_level0_entry02(self): self.assertNoFormError(response2) self.assertEqual(4, MenuConfigItem.objects.count()) - items = [ - *MenuConfigItem.objects.exclude( - id__in=[special_item1.id, container.id, item.id], - ), - ] - self.assertEqual(1, len(items)) - special_item2 = items[0] + special_item2 = self.get_alone_element(MenuConfigItem.objects.exclude( + id__in=[special_item1.id, container.id, item.id], + )) self.assertEqual('creme_core-recent_entities', special_item2.entry_id) self.assertEqual(21, special_item2.order) @@ -900,10 +893,7 @@ def test_add_special_level0_entry04(self): entry_id = CremeEntry.id self.assertNoFormError(self.client.post(url, data={'entry_id': entry_id})) - items = [*MenuConfigItem.objects.all()] - self.assertEqual(1, len(items)) - - special_item = items[0] + special_item = self.get_alone_element(MenuConfigItem.objects.all()) self.assertEqual('creme_core-creme', special_item.entry_id) self.assertEqual(0, special_item.order) self.assertDictEqual({}, special_item.entry_data) @@ -938,10 +928,7 @@ def test_add_special_level0_entry05(self): entry_id = CremeEntry.id self.assertNoFormError(self.client.post(url, data={'entry_id': entry_id})) - items = [*MenuConfigItem.objects.all()] - self.assertEqual(1, len(items)) - - special_item = items[0] + special_item = self.get_alone_element(MenuConfigItem.objects.all()) self.assertEqual('creme_core-creme', special_item.entry_id) self.assertEqual(0, special_item.order) self.assertDictEqual({}, special_item.entry_data) diff --git a/creme/creme_config/tests/test_registry.py b/creme/creme_config/tests/test_registry.py index b9e554dd51..3d26e8d8a4 100644 --- a/creme/creme_config/tests/test_registry.py +++ b/creme/creme_config/tests/test_registry.py @@ -51,16 +51,11 @@ def test_register_model01(self): model_name = 'civility' registry.register_model(FakeCivility, model_name=model_name) - app_registries = [*registry.apps()] - self.assertEqual(1, len(app_registries)) - app_registry = app_registries[0] + app_registry = self.get_alone_element(registry.apps()) self.assertEqual('creme_core', app_registry.name) - model_configs = [*app_registry.models()] - self.assertEqual(1, len(model_configs)) - - model_config = model_configs[0] + model_config = self.get_alone_element(app_registry.models()) self.assertEqual(FakeCivility, model_config.model) self.assertEqual(model_name, model_config.model_name) diff --git a/creme/creme_config/tests/test_relation_type.py b/creme/creme_config/tests/test_relation_type.py index e12cbd216b..7476fc8cbe 100644 --- a/creme/creme_config/tests/test_relation_type.py +++ b/creme/creme_config/tests/test_relation_type.py @@ -358,10 +358,7 @@ def test_create01(self): ) self.assertNoFormError(response) - semi_fixed_relations = SemiFixedRelationType.objects.all() - self.assertEqual(1, len(semi_fixed_relations)) - - smr = semi_fixed_relations[0] + smr = self.get_alone_element(SemiFixedRelationType.objects.all()) self.assertEqual(predicate, smr.predicate) self.assertEqual(self.loves, smr.relation_type) self.assertEqual(iori.entity_type, smr.object_ctype) diff --git a/creme/creme_config/tests/test_search.py b/creme/creme_config/tests/test_search.py index a0ce35ebea..ba95105db4 100644 --- a/creme/creme_config/tests/test_search.py +++ b/creme/creme_config/tests/test_search.py @@ -134,10 +134,7 @@ def test_add01(self): }, )) - sc_items = SearchConfigItem.objects.filter(content_type=ct) - self.assertEqual(1, len(sc_items)) - - sc_item = sc_items[0] + sc_item = self.get_alone_element(SearchConfigItem.objects.filter(content_type=ct)) self.assertEqual(role, sc_item.role) self.assertFalse(sc_item.superuser) self.assertFalse(sc_item.disabled) @@ -267,14 +264,13 @@ def test_add_custom_fields(self): }, )) - sc_items = SearchConfigItem.objects.filter(content_type=ct) - self.assertEqual(1, len(sc_items)) + sc_item = self.get_alone_element(SearchConfigItem.objects.filter(content_type=ct)) self.assertListEqual( [ EntityCellCustomField(cf) for cf in (cfield1, cfield2, cfield3, cfield4) ], - [*sc_items[0].cells], + [*sc_item.cells], ) def test_add_custom_fields_errors(self): @@ -284,7 +280,7 @@ def test_add_custom_fields_errors(self): def post(cfield): response = self.assertPOST200( self._build_add_url(ct), - data={'cells': f'custom_field-{cfield.id}'} + data={'cells': f'custom_field-{cfield.id}'}, ) self.assertFormError( response.context['form'], diff --git a/creme/creme_config/tests/test_user.py b/creme/creme_config/tests/test_user.py index 552783590f..db1be48912 100644 --- a/creme/creme_config/tests/test_user.py +++ b/creme/creme_config/tests/test_user.py @@ -375,10 +375,7 @@ def test_create_user01(self): ) self.assertNoFormError(response) - users = User.objects.filter(username=username) - self.assertEqual(1, len(users)) - - user = users[0] + user = self.get_alone_element(User.objects.filter(username=username)) self.assertTrue(user.is_superuser) self.assertIsNone(user.role) self.assertEqual(first_name, user.first_name) @@ -1192,10 +1189,7 @@ def test_create_team01(self): data={'username': 'Team-A', 'teammates': [user01.id, user02.id]}, )) - teams = User.objects.filter(is_team=True) - self.assertEqual(1, len(teams)) - - team = teams[0] + team = self.get_alone_element(User.objects.filter(is_team=True)) self.assertFalse(team.is_superuser) self.assertEqual('', team.first_name) self.assertEqual('', team.last_name) @@ -1436,10 +1430,7 @@ def test_delete_last_superuser(self): "Delete view can not delete the last superuser." self.client.login(username='root', password='root') - superusers = User.objects.filter(is_superuser=True) - self.assertEqual(1, len(superusers)) - - user = superusers[0] + user = self.get_alone_element(User.objects.filter(is_superuser=True)) url = self._build_delete_url(user) self.assertGET409(url) diff --git a/creme/creme_config/tests/test_user_role.py b/creme/creme_config/tests/test_user_role.py index 5993618f48..91736d77a5 100644 --- a/creme/creme_config/tests/test_user_role.py +++ b/creme/creme_config/tests/test_user_role.py @@ -263,10 +263,7 @@ def test_creation_wizard01(self): self.assertCountEqual([ct_contact, ct_doc], role.creatable_ctypes.all()) self.assertCountEqual([ct_contact], role.exportable_ctypes.all()) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - creds = setcreds[0] + creds = self.get_alone_element(role.credentials.all()) self.assertEqual(EntityCredentials.VIEW | EntityCredentials.CHANGE, creds.value) self.assertEqual(set_type, creds.set_type) self.assertEqual(ct_contact, creds.ctype) @@ -376,10 +373,7 @@ def test_creation_wizard02(self): self.assertFalse(role.creatable_ctypes.all()) self.assertFalse(role.exportable_ctypes.all()) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - creds = setcreds[0] + creds = self.get_alone_element(role.credentials.all()) self.assertEqual(set_type, creds.set_type) self.assertEqual(ct_contact, creds.ctype) self.assertTrue(creds.forbidden) @@ -393,10 +387,7 @@ def test_creation_wizard02(self): self.assertEqual(filter_name, efilter.name) self.assertTrue(efilter.use_or) - conditions = efilter.get_conditions() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.get_conditions()) self.assertEqual( condition_handler.RegularFieldConditionHandler.type_id, condition.type, @@ -488,20 +479,15 @@ def test_creation_wizard03(self): self.assertNoFormError(response) role = self.get_object_or_fail(UserRole, name=name) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - creds = setcreds[0] + creds = self.get_alone_element(role.credentials.all()) self.assertIsNone(creds.ctype) # CremeEntity efilter = creds.efilter self.assertIsNotNone(efilter) self.assertEqual(CremeEntity, efilter.entity_type.model_class()) - conditions = efilter.get_conditions() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.get_conditions()) self.assertEqual( condition_handler.RegularFieldConditionHandler.type_id, condition.type, @@ -597,10 +583,7 @@ def test_add_credentials01(self): }, )) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - creds = setcreds[0] + creds = self.get_alone_element(role.credentials.all()) self.assertEqual(EntityCredentials.VIEW, creds.value) self.assertEqual(set_type, creds.set_type) self.assertIsNone(creds.ctype) @@ -665,10 +648,7 @@ def test_add_credentials02(self): ) self.assertNoFormError(response) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - creds = setcreds[0] + creds = self.get_alone_element(role.credentials.all()) self.assertEqual(EntityCredentials.VIEW | EntityCredentials.CHANGE, creds.value) self.assertEqual(SetCredentials.ESET_OWN, creds.set_type) self.assertEqual(ct_contact.id, creds.ctype_id) @@ -742,10 +722,7 @@ def test_add_credentials04(self): ) self.assertNoFormError(response) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - creds = setcreds[0] + creds = self.get_alone_element(role.credentials.all()) self.assertEqual(EntityCredentials.VIEW | EntityCredentials.CHANGE, creds.value) self.assertEqual(set_type, creds.set_type) self.assertEqual(ct_contact.id, creds.ctype_id) @@ -864,10 +841,7 @@ def test_add_credentials_with_filter01(self): ) self.assertNoFormError(response) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - creds = setcreds[0] + creds = self.get_alone_element(role.credentials.all()) self.assertEqual(EntityCredentials.VIEW | EntityCredentials.CHANGE, creds.value) self.assertEqual(set_type, creds.set_type) self.assertEqual(ctype.id, creds.ctype_id) @@ -880,10 +854,7 @@ def test_add_credentials_with_filter01(self): self.assertEqual(f'creme_core-credentials_{role.id}-1', efilter.id) self.assertEqual(EF_CREDENTIALS, efilter.filter_type) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual( condition_handler.RegularFieldConditionHandler.type_id, condition.type, @@ -962,10 +933,7 @@ def test_add_credentials_with_filter02(self): ) self.assertNoFormError(response) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - creds = setcreds[0] + creds = self.get_alone_element(role.credentials.all()) self.assertEqual(EntityCredentials.DELETE, creds.value) self.assertEqual(set_type, creds.set_type) self.assertEqual(ctype.id, creds.ctype_id) @@ -1070,10 +1038,7 @@ def test_add_credentials_with_filter03(self): ) self.assertNoFormError(response) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - creds = setcreds[0] + creds = self.get_alone_element(role.credentials.all()) self.assertEqual( EntityCredentials.VIEW | EntityCredentials.CHANGE | EntityCredentials.DELETE, creds.value, @@ -1084,10 +1049,7 @@ def test_add_credentials_with_filter03(self): efilter = creds.efilter self.assertIsInstance(efilter, EntityFilter) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual( condition_handler.RegularFieldConditionHandler.type_id, condition.type, @@ -1315,10 +1277,7 @@ def test_edit_credentials_with_filter01(self): ) self.assertNoFormError(response) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - efilter = setcreds[0].efilter + efilter = self.get_alone_element(role.credentials.all()).efilter self.assertIsInstance(efilter, EntityFilter) self.assertEqual(name, efilter.name) self.assertTrue(efilter.use_or) @@ -1328,10 +1287,7 @@ def test_edit_credentials_with_filter01(self): ) self.assertEqual(EF_CREDENTIALS, efilter.filter_type) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual( condition_handler.RegularFieldConditionHandler.type_id, condition.type, @@ -1451,10 +1407,7 @@ def test_edit_credentials_with_filter02(self): ) self.assertNoFormError(response) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - set_cred2 = setcreds[0] + set_cred2 = self.get_alone_element(role.credentials.all()) self.assertEqual(set_cred1.ctype, set_cred2.ctype) efilter2 = set_cred2.efilter @@ -1584,10 +1537,7 @@ def test_edit_credentials_with_filter03(self): ) self.assertNoFormError(response) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - setcred = setcreds[0] + setcred = self.get_alone_element(role.credentials.all()) self.assertEqual(ctype, setcred.ctype) efilter2 = setcred.efilter @@ -1598,10 +1548,7 @@ def test_edit_credentials_with_filter03(self): self.assertEqual(EF_CREDENTIALS, efilter2.filter_type) self.assertEqual(efilter1.id, efilter2.id) - conditions = efilter2.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter2.conditions.all()) self.assertEqual( condition_handler.PropertyConditionHandler.type_id, condition.type, @@ -1758,11 +1705,10 @@ def test_edit_credentials_with_filter05(self): }, )) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - self.assertIsNone(setcreds[0].ctype) + setcreds = self.get_alone_element(role.credentials.all()) + self.assertIsNone(setcreds.ctype) - efilter2 = setcreds[0].efilter + efilter2 = setcreds.efilter self.assertIsNotNone(efilter2) self.assertEqual( ContentType.objects.get_for_model(CremeEntity), @@ -1771,10 +1717,7 @@ def test_edit_credentials_with_filter05(self): self.assertEqual(name, efilter2.name) self.assertTrue(efilter2.use_or) - conditions = efilter2.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter2.conditions.all()) self.assertEqual( condition_handler.PropertyConditionHandler.type_id, condition.type, @@ -1833,20 +1776,14 @@ def test_edit_credentials_with_filter06(self): ) self.assertNoFormError(response) - setcreds = role.credentials.all() - self.assertEqual(1, len(setcreds)) - - efilter = setcreds[0].efilter + efilter = self.get_alone_element(role.credentials.all()).efilter self.assertEqual(name, efilter.name) self.assertEqual( ContentType.objects.get_for_model(CremeEntity), efilter.entity_type, ) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual( condition_handler.RegularFieldConditionHandler.type_id, condition.type, diff --git a/creme/creme_config/tests/transfer/test_exporting.py b/creme/creme_config/tests/transfer/test_exporting.py index f818beece5..e602d5b87e 100644 --- a/creme/creme_config/tests/transfer/test_exporting.py +++ b/creme/creme_config/tests/transfer/test_exporting.py @@ -167,10 +167,7 @@ class TestExporter02(Exporter): def dump_instance(self, instance): return [{'value': 2}] - exporters = [*registry] - self.assertEqual(1, len(exporters)) - - item = exporters[0] + item = self.get_alone_element(registry) self.assertEqual(data_id, item[0]) self.assertIsInstance(item[1], TestExporter02) @@ -190,10 +187,7 @@ class TestExporter02(Exporter): def dump_instance(self, instance): return [{'value': 2}] - exporters = [*registry] - self.assertEqual(1, len(exporters)) - - item = exporters[0] + item = self.get_alone_element(registry) self.assertEqual(data_id, item[0]) self.assertIsInstance(item[1], TestExporter01) @@ -211,9 +205,8 @@ def exporter2(): return [{'value': 2}] registry.unregister(data_id1) - exporters = [*registry] - self.assertEqual(1, len(exporters)) - self.assertEqual(data_id2, exporters[0][0]) + item = self.get_alone_element(registry) + self.assertEqual(data_id2, item[0]) def test_unregister02(self): "Un-register before." @@ -231,9 +224,8 @@ def exporter1(): def exporter2(): return [{'value': 2}] - exporters = [*registry] - self.assertEqual(1, len(exporters)) - self.assertEqual(data_id2, exporters[0][0]) + item = self.get_alone_element(registry) + self.assertEqual(data_id2, item[0]) def test_roles(self): "Roles." @@ -398,9 +390,7 @@ def test_relation_bricks(self): if dumped_rbi['relation_type'] == rtype01.id ] - self.assertEqual(1, len(all_rbi_info01)) - - rbi_info01 = all_rbi_info01[0] + rbi_info01 = self.get_alone_element(all_rbi_info01) self.assertEqual(rbi1.id, rbi_info01.get('id')) self.assertNotIn('cells', rbi_info01) @@ -412,9 +402,7 @@ def test_relation_bricks(self): if dumped_rbi['relation_type'] == rtype02.id ] - self.assertEqual(1, len(all_rbi_info02)) - - rbi_info02 = all_rbi_info02[0] + rbi_info02 = self.get_alone_element(all_rbi_info02) # self.assertEqual(rtype_brick_id02, rbi_info02.get('brick_id')) self.assertEqual(rbi2.id, rbi_info02.get('id')) @@ -474,9 +462,7 @@ def test_custom_bricks(self): if dumped_cbci['id'] == cbci.id ] - self.assertEqual(1, len(all_cbci_info01)) - - cbci_info = all_cbci_info01[0] + cbci_info = self.get_alone_element(all_cbci_info01) self.assertEqual('creme_core.fakecontact', cbci_info.get('content_type')) self.assertEqual(cbci.name, cbci_info.get('name')) self.assertListEqual( diff --git a/creme/creme_config/tests/transfer/test_importing.py b/creme/creme_config/tests/transfer/test_importing.py index ef0d0df0a7..c7cec89c90 100644 --- a/creme/creme_config/tests/transfer/test_importing.py +++ b/creme/creme_config/tests/transfer/test_importing.py @@ -139,9 +139,8 @@ class TestImporter01(Importer): class TestImporter02(Importer): pass - importers = registry.build_importers() - self.assertEqual(1, len(importers)) - self.assertIsInstance(importers[0], TestImporter02) + importer = self.get_alone_element(registry.build_importers()) + self.assertIsInstance(importer, TestImporter02) def test_register04(self): "Priority (stronger before)." @@ -157,9 +156,8 @@ class TestImporter01(Importer): class TestImporter02(Importer): pass - importers = registry.build_importers() - self.assertEqual(1, len(importers)) - self.assertIsInstance(importers[0], TestImporter01) + importer = self.get_alone_element(registry.build_importers()) + self.assertIsInstance(importer, TestImporter01) def test_unregister01(self): registry = ImportersRegistry() @@ -176,9 +174,8 @@ class TestImporter02(Importer): registry.unregister(data_id1) - importers = registry.build_importers() - self.assertEqual(1, len(importers)) - self.assertIsInstance(importers[0], TestImporter02) + importer = self.get_alone_element(registry.build_importers()) + self.assertIsInstance(importer, TestImporter02) def test_unregister02(self): "Un-register before." @@ -196,9 +193,8 @@ class TestImporter01(Importer): class TestImporter02(Importer): pass - importers = registry.build_importers() - self.assertEqual(1, len(importers)) - self.assertIsInstance(importers[0], TestImporter02) + importer = self.get_alone_element(registry.build_importers()) + self.assertIsInstance(importer, TestImporter02) def test_dependencies(self): registry = ImportersRegistry() @@ -340,37 +336,33 @@ def test_roles01(self): self.assertEqual(3, len(credentials)) # -- - own_creds = [ + own_creds = self.get_alone_element( sc for sc in credentials if sc.set_type == SetCredentials.ESET_OWN and not sc.forbidden - ] - self.assertEqual(1, len(own_creds)) + ) self.assertEqual( EntityCredentials.VIEW | EntityCredentials.CHANGE | EntityCredentials.LINK, - own_creds[0].value + own_creds.value, ) - self.assertFalse(own_creds[0].ctype) + self.assertFalse(own_creds.ctype) # -- - all_creds = [sc for sc in credentials if sc.set_type == SetCredentials.ESET_ALL] - self.assertEqual(1, len(all_creds)) - creds2 = all_creds[0] + all_creds = self.get_alone_element( + sc for sc in credentials if sc.set_type == SetCredentials.ESET_ALL + ) self.assertEqual( EntityCredentials.VIEW | EntityCredentials.CHANGE | EntityCredentials.DELETE, - creds2.value + all_creds.value ) - self.assertEqual(contact_ct, creds2.ctype) - self.assertFalse(creds2.forbidden) + self.assertEqual(contact_ct, all_creds.ctype) + self.assertFalse(all_creds.forbidden) # -- - forbidden_creds = [sc for sc in credentials if sc.forbidden] - self.assertEqual(1, len(own_creds)) - - creds3 = forbidden_creds[0] - self.assertEqual(SetCredentials.ESET_OWN, creds3.set_type) - self.assertEqual(EntityCredentials.CHANGE, creds3.value) - self.assertEqual(orga_ct, creds3.ctype) + forbidden_creds = self.get_alone_element(sc for sc in credentials if sc.forbidden) + self.assertEqual(SetCredentials.ESET_OWN, forbidden_creds.set_type) + self.assertEqual(EntityCredentials.CHANGE, forbidden_creds.value) + self.assertEqual(orga_ct, forbidden_creds.ctype) def test_roles02(self): "Role with same name already exists => override it." @@ -431,10 +423,7 @@ def test_roles02(self): self.assertCountEqual([contact_ct, orga_ct], role.creatable_ctypes.all()) self.assertCountEqual([orga_ct], role.exportable_ctypes.all()) - all_credentials = [*role.credentials.all()] - self.assertEqual(1, len(all_credentials)) - - credentials = all_credentials[0] + credentials = self.get_alone_element(role.credentials.all()) self.assertEqual( EntityCredentials.VIEW | EntityCredentials.CHANGE | EntityCredentials.DELETE, credentials.value, @@ -516,20 +505,14 @@ def test_roles03(self): self.assertIsNone(efilter.user) self.assertFalse(efilter.is_private) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition1 = conditions[0] - self.assertEqual(RelationConditionHandler.type_id, condition1.type) - self.assertEqual(rtype_id, condition1.name) + condition = self.get_alone_element(efilter.conditions.all()) + self.assertEqual(RelationConditionHandler.type_id, condition.type) + self.assertEqual(rtype_id, condition.name) # --- role = self.get_object_or_fail(UserRole, name=role_name) - all_credentials = [*role.credentials.all()] - self.assertEqual(1, len(all_credentials)) - - credentials = all_credentials[0] + credentials = self.get_alone_element(role.credentials.all()) self.assertEqual( EntityCredentials.VIEW | EntityCredentials.CHANGE, credentials.value, @@ -713,10 +696,7 @@ def test_menu(self): self.assertEqual(2, super_item2.order) self.assertDictEqual({'label': container_label2}, super_item2.entry_data) - super_children = super_item2.children.all() - self.assertEqual(1, len(super_children)) - - super_child1 = super_children[0] + super_child1 = self.get_alone_element(super_item2.children.all()) self.assertEqual(FakeContactsEntry.id, super_child1.entry_id) self.assertEqual(1, super_child1.order) self.assertTrue(super_child1.superuser) @@ -732,10 +712,7 @@ def test_menu(self): role1_item2 = role1_items[1] self.assertEqual(ContainerEntry.id, role1_item2.entry_id) - role1_children = role1_item2.children.all() - self.assertEqual(1, len(role1_children)) - - role1_child1 = role1_children[0] + role1_child1 = self.get_alone_element(role1_item2.children.all()) self.assertEqual(FakeContactsEntry.id, role1_child1.entry_id) self.assertFalse(role1_child1.superuser) self.assertEqual(role1, role1_child1.role) @@ -751,10 +728,7 @@ def test_menu(self): role2_item2 = role2_items[1] self.assertEqual(ContainerEntry.id, role2_item2.entry_id) - role2_children = role2_item2.children.all() - self.assertEqual(1, len(role2_children)) - - role2_child1 = role2_children[0] + role2_child1 = self.get_alone_element(role2_item2.children.all()) self.assertEqual(FakeOrganisationsEntry.id, role2_child1.entry_id) self.assertFalse(role2_child1.superuser) self.assertEqual(role2, role2_child1.role) @@ -2252,10 +2226,7 @@ def test_entityfilters03(self): ef2 = self.get_object_or_fail(EntityFilter, id=efilters_data[0]['id']) ef3 = self.get_object_or_fail(EntityFilter, id=efilters_data[1]['id']) - conditions2 = ef2.conditions.all() - self.assertEqual(1, len(conditions2)) - - condition2_1 = conditions2[0] + condition2_1 = self.get_alone_element(ef2.conditions.all()) self.assertEqual(SubFilterConditionHandler.type_id, condition2_1.type) self.assertEqual(ef3.id, condition2_1.name) @@ -2340,10 +2311,7 @@ def test_entityfilters04(self): ef2 = self.get_object_or_fail(EntityFilter, id=efilters_data[0]['id']) ef3 = self.get_object_or_fail(EntityFilter, id=efilters_data[1]['id']) - conditions2 = ef2.conditions.all() - self.assertEqual(1, len(conditions2)) - - condition2_1 = conditions2[0] + condition2_1 = self.get_alone_element(ef2.conditions.all()) self.assertEqual(RelationSubFilterConditionHandler.type_id, condition2_1.type) self.assertEqual(rtype.id, condition2_1.name) self.assertDictEqual({'has': False, 'filter_id': ef3.id}, condition2_1.value) @@ -2351,10 +2319,7 @@ def test_entityfilters04(self): # -- ef4 = self.get_object_or_fail(EntityFilter, id=efilters_data[2]['id']) - conditions4 = ef4.conditions.all() - self.assertEqual(1, len(conditions4)) - - condition4_1 = conditions4[0] + condition4_1 = self.get_alone_element(ef4.conditions.all()) self.assertEqual(RelationSubFilterConditionHandler.type_id, condition4_1.type) self.assertEqual(rtype.id, condition4_1.name) self.assertDictEqual({'has': True, 'filter_id': ef1.id}, condition4_1.value) @@ -2831,10 +2796,7 @@ def test_customforms(self): descriptor_id=desc.id, role=None, superuser=True, ) - groups2 = desc.groups(cfci02) - self.assertEqual(1, len(groups2)) - - group21 = groups2[0] + group21 = self.get_alone_element(desc.groups(cfci02)) self.assertEqual(gname2, group21.name) self.assertEqual(LAYOUT_REGULAR, group21.layout) self.assertListEqual( diff --git a/creme/creme_core/tests/base.py b/creme/creme_core/tests/base.py index 4b25ea789d..8f5afa29f9 100644 --- a/creme/creme_core/tests/base.py +++ b/creme/creme_core/tests/base.py @@ -693,6 +693,15 @@ def get_object_or_fail(self, model, **kwargs): return obj + def get_alone_element(self, iterable): + """Check that an iterable has only one element, which is returned.""" + listified = [*iterable] + length = len(listified) + if length != 1: + self.fail(f'The iterable has {length} elements, not 1') + + return listified[0] + def get_choices_group_or_fail(self, label, choices): for choice in choices: if choice[0] == label: diff --git a/creme/creme_core/tests/core/test_entity_cell.py b/creme/creme_core/tests/core/test_entity_cell.py index 59e4974ac3..fcc866d12a 100644 --- a/creme/creme_core/tests/core/test_entity_cell.py +++ b/creme/creme_core/tests/core/test_entity_cell.py @@ -190,9 +190,8 @@ def test_registry_build_cells_from_dicts02(self): ], ) self.assertIs(errors, True) - self.assertEqual(1, len(cells)) - cell = cells[0] + cell = self.get_alone_element(cells) self.assertIsInstance(cell, EntityCellFunctionField) self.assertEqual(FakeDocument, cell.model) self.assertEqual('get_pretty_properties', cell.value) @@ -246,9 +245,8 @@ def test_registry_build_cells_from_keys02(self): ], ) self.assertIs(errors, True) - self.assertEqual(1, len(cells)) - cell = cells[0] + cell = self.get_alone_element(cells) self.assertIsInstance(cell, EntityCellFunctionField) self.assertEqual(FakeDocument, cell.model) self.assertEqual('get_pretty_properties', cell.value) diff --git a/creme/creme_core/tests/core/test_paginator.py b/creme/creme_core/tests/core/test_paginator.py index 1440ccf0f4..a6b0a7bfa7 100644 --- a/creme/creme_core/tests/core/test_paginator.py +++ b/creme/creme_core/tests/core/test_paginator.py @@ -519,9 +519,8 @@ def test_no_offset(self): with context: paginator.page(info) - queries = context.captured_sql - self.assertEqual(1, len(queries)) - self.assertNotIn('OFFSET', queries[0]) + query = self.get_alone_element(context.captured_sql) + self.assertNotIn('OFFSET', query) def test_previous_page01(self): self._build_contacts() diff --git a/creme/creme_core/tests/forms/test_entity_cell.py b/creme/creme_core/tests/forms/test_entity_cell.py index f1c3c0bad1..801786ebd1 100644 --- a/creme/creme_core/tests/forms/test_entity_cell.py +++ b/creme/creme_core/tests/forms/test_entity_cell.py @@ -574,10 +574,7 @@ def test_ok01(self): "One regular field." field = EntityCellsField(model=FakeContact) fname = 'first_name' - cells = field.clean(f'regular_field-{fname}') - self.assertEqual(1, len(cells)) - - cell = cells[0] + cell = self.get_alone_element(field.clean(f'regular_field-{fname}')) self.assertEqual(EntityCellRegularField.build(FakeContact, fname), cell) self.assertIs(cell.is_hidden, False) diff --git a/creme/creme_core/tests/forms/test_entity_filter.py b/creme/creme_core/tests/forms/test_entity_filter.py index 7d7ae807b5..7026eda223 100644 --- a/creme/creme_core/tests/forms/test_entity_filter.py +++ b/creme/creme_core/tests/forms/test_entity_filter.py @@ -303,14 +303,13 @@ def test_iequals_condition(self): operator = operators.IEQUALS name = 'first_name' value = 'Faye' - conditions = field.clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': value, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + field.clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': value, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertEqual(EF_USER, condition.filter_type) @@ -330,14 +329,13 @@ def test_initialize(self): operator = operators.IEQUALS name = 'first_name' value = 'Faye' - conditions = field.clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': value, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + field.clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': value, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertEqual(EF_CREDENTIALS, condition.filter_type) @@ -355,14 +353,13 @@ def test_iequals_condition_multiple_as_string(self): name = 'first_name' faye_name = 'Faye' ed_name = 'Ed' - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': f'{faye_name},{ed_name}', - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': f'{faye_name},{ed_name}', + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -379,14 +376,13 @@ def test_iequals_condition_multiple_as_list(self): name = 'first_name' faye_name = 'Faye' ed_name = 'Ed' - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': [faye_name, ed_name], - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': [faye_name, ed_name], + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -402,14 +398,13 @@ def test_isempty_condition(self): ).clean operator = operators.ISEMPTY name = 'description' - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': True, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': True, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -425,14 +420,13 @@ def test_isnotempty_condition(self): ).clean operator = operators.ISEMPTY name = 'description' - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': False, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': False, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -447,14 +441,13 @@ def test_equals_boolean_condition(self): ).clean operator = operators.EQUALS name = 'subject_to_vat' - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': True, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': True, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -470,14 +463,13 @@ def test_fk_subfield(self): operator = operators.ISTARTSWITH name = 'civility__title' value = 'Miss' - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': value, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': value, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -494,14 +486,13 @@ def test_fk(self): operator = operators.EQUALS name = 'civility' value = FakeCivility.objects.all()[0].pk - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': value, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': value, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -516,14 +507,13 @@ def test_multiple_fk_as_string(self): operator = operators.EQUALS name = 'civility' values = [c.pk for c in FakeCivility.objects.all()] - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': ','.join(str(v) for v in values), - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': ','.join(str(v) for v in values), + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -539,14 +529,13 @@ def test_multiple_fk_as_list(self): operator = operators.EQUALS name = 'civility' values = [str(c.pk) for c in FakeCivility.objects.all()] - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': values, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': values, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -562,14 +551,13 @@ def test_many2many(self): operator = operators.EQUALS name = 'languages' value = Language.objects.all()[0].pk - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': value, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': value, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -585,14 +573,13 @@ def test_multiple_many2many_as_list(self): operator = operators.EQUALS name = 'languages' values = [str(v) for v in Language.objects.all().values_list('pk', flat=True)] - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': values, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': values, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -609,14 +596,13 @@ def test_multiple_many2many_as_string(self): operator = operators.EQUALS name = 'languages' values = Language.objects.all().values_list('pk', flat=True) - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': ','.join(str(v) for v in values), - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': ','.join(str(v) for v in values), + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -636,14 +622,13 @@ def test_static_choices(self): operator = operators.EQUALS name = 'discount_unit' value = FakeInvoiceLine.Discount.AMOUNT - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': value, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': value, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -689,14 +674,13 @@ def test_iendswith_valuelist(self): operator = operators.IENDSWITH name = 'last_name' values = ['nagi', 'sume'] - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': ','.join(values), - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': ','.join(values), + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -756,14 +740,13 @@ def test_many2many_subfield(self): operator = operators.IEQUALS name = 'languages__name' value = 'French' - conditions = clean(self.build_data({ - 'operator': operator, - 'name': name, - 'value': value, - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data({ + 'operator': operator, + 'name': name, + 'value': value, + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -861,14 +844,13 @@ def test_fields_config03(self): ], ) - conditions = field.clean(self.build_data({ - 'operator': operators.EQUALS, - 'name': hidden_fname, - 'value': 'Faye', - })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + field.clean(self.build_data({ + 'operator': operators.EQUALS, + 'name': hidden_fname, + 'value': 'Faye', + })) + ) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(hidden_fname, condition.name) @@ -899,9 +881,7 @@ def test_fields_config04(self): 'value': 'Faye', })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(conditions) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(hidden_sfname, condition.name) @@ -932,9 +912,7 @@ def test_fields_config05(self): 'value': 'Faye', })) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(conditions) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(hidden_sfname, condition.name) @@ -965,9 +943,8 @@ def test_fields_config06(self): 'name': hidden_fname, 'value': str(position.id), })) - self.assertEqual(1, len(conditions)) - condition = conditions[0] + condition = self.get_alone_element(conditions) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(hidden_fname, condition.name) @@ -1103,17 +1080,16 @@ def test_ok03(self): "Start + end." clean = DateFieldsConditionsField(model=FakeContact).clean name = 'modified' - conditions = clean(json_dump([{ - 'field': {'name': name, 'type': 'date'}, - 'range': { - 'type': '', - 'start': self.formfield_value_date(2010, 3, 24), - 'end': self.formfield_value_date(2011, 7, 25), - }, - }])) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(json_dump([{ + 'field': {'name': name, 'type': 'date'}, + 'range': { + 'type': '', + 'start': self.formfield_value_date(2010, 3, 24), + 'end': self.formfield_value_date(2011, 7, 25), + }, + }])) + ) self.assertEqual(DateRegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertDictEqual( @@ -1169,10 +1145,7 @@ def build_data(fname): }, }]) - conditions = field.clean(build_data(valid_fname)) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(field.clean(build_data(valid_fname))) self.assertEqual(DateRegularFieldConditionHandler.type_id, condition.type) self.assertEqual(valid_fname, condition.name) @@ -1204,10 +1177,7 @@ def build_data(fname): }]) clean = DateFieldsConditionsField(model=FakeInvoiceLine).clean - conditions = clean(build_data(valid_fname)) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(clean(build_data(valid_fname))) self.assertEqual(DateRegularFieldConditionHandler.type_id, condition.type) self.assertEqual(valid_fname, condition.name) @@ -1271,9 +1241,7 @@ def test_fields_config04(self): 'range': {'type': '', 'start': self.formfield_value_date(2000, 1, 1)}, }])) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(conditions) self.assertEqual(DateRegularFieldConditionHandler.type_id, condition.type) self.assertEqual(hidden_fname, condition.name) @@ -1303,9 +1271,7 @@ def test_fields_config05(self): 'range': {'type': '', 'start': self.formfield_value_date(2000, 1, 1)}, }])) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(conditions) self.assertEqual(DateRegularFieldConditionHandler.type_id, condition.type) self.assertEqual(hidden_sfname, condition.name) @@ -1334,9 +1300,7 @@ def test_fields_config06(self): 'range': {'type': '', 'start': self.formfield_value_date(2000, 1, 1)}, }])) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(conditions) self.assertEqual(DateRegularFieldConditionHandler.type_id, condition.type) self.assertEqual(hidden_sfname, condition.name) @@ -1600,14 +1564,13 @@ def test_clean_integer01(self): operator = operators.EQUALS value = 180 - conditions = field.clean(self.build_data( - field=self.cfield_int.id, - operator=operator, - value=value, - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + field.clean(self.build_data( + field=self.cfield_int.id, + operator=operator, + value=value, + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(self.cfield_int.id), condition.name) self.assertEqual(EF_USER, condition.filter_type) @@ -1631,14 +1594,13 @@ def test_clean_integer02(self): operator = operators.EQUALS value = 180 - conditions = field.clean(self.build_data( - field=self.cfield_int.id, - operator=operator, - value=value, - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + field.clean(self.build_data( + field=self.cfield_int.id, + operator=operator, + value=value, + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(self.cfield_int.id), condition.name) self.assertEqual(EF_CREDENTIALS, condition.filter_type) @@ -1658,14 +1620,13 @@ def test_clean_enum(self): ).clean operator = operators.EQUALS value = str(self.cfield_enum_A.pk) - conditions = clean(self.build_data( - field=self.cfield_enum.id, - operator=operator, - value=value, - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data( + field=self.cfield_enum.id, + operator=operator, + value=value, + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(self.cfield_enum.id), condition.name) self.assertDictEqual( @@ -1683,14 +1644,13 @@ def test_clean_enum_as_string(self): efilter_registry=efilter_registry, ).clean operator = operators.EQUALS - conditions = clean(self.build_data( - field=self.cfield_enum.id, - operator=operator, - value=f'{self.cfield_enum_A.pk},{self.cfield_enum_B.pk}', - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data( + field=self.cfield_enum.id, + operator=operator, + value=f'{self.cfield_enum_A.pk},{self.cfield_enum_B.pk}', + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(self.cfield_enum.id), condition.name) self.assertDictEqual( @@ -1711,14 +1671,13 @@ def test_clean_enum_as_list(self): efilter_registry=efilter_registry, ).clean operator = operators.EQUALS - conditions = clean(self.build_data( - field=self.cfield_enum.id, - operator=operator, - value=[self.cfield_enum_A.pk, self.cfield_enum_B.pk], - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data( + field=self.cfield_enum.id, + operator=operator, + value=[self.cfield_enum_A.pk, self.cfield_enum_B.pk], + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(self.cfield_enum.id), condition.name) self.assertDictEqual( @@ -1739,14 +1698,13 @@ def test_clean_multienum(self): ).clean operator = operators.EQUALS value = str(self.cfield_multienum_F.pk) - conditions = clean(self.build_data( - field=self.cfield_multienum.id, - operator=operator, - value=value, - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data( + field=self.cfield_multienum.id, + operator=operator, + value=value, + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(self.cfield_multienum.id), condition.name) self.assertDictEqual( @@ -1763,14 +1721,13 @@ def test_clean_multienum_as_string(self): model=FakeContact, efilter_registry=efilter_registry, ).clean operator = operators.EQUALS - conditions = clean(self.build_data( - field=self.cfield_multienum.id, - operator=operator, - value=f'{self.cfield_multienum_F.pk},{self.cfield_multienum_H.pk}', - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data( + field=self.cfield_multienum.id, + operator=operator, + value=f'{self.cfield_multienum_F.pk},{self.cfield_multienum_H.pk}', + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(self.cfield_multienum.id), condition.name) self.assertDictEqual( @@ -1790,17 +1747,16 @@ def test_clean_multienum_as_list(self): model=FakeContact, efilter_registry=efilter_registry, ).clean operator = operators.EQUALS - conditions = clean(self.build_data( - field=self.cfield_multienum.id, - operator=operator, - value=[ - self.cfield_multienum_F.pk, - self.cfield_multienum_H.pk, - ], - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data( + field=self.cfield_multienum.id, + operator=operator, + value=[ + self.cfield_multienum_F.pk, + self.cfield_multienum_H.pk, + ], + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(self.cfield_multienum.id), condition.name) self.assertDictEqual( @@ -1820,14 +1776,13 @@ def test_clean_empty_string(self): model=FakeContact, efilter_registry=efilter_registry, ).clean operator = operators.EQUALS - conditions = clean(self.build_data( - field=self.cfield_str.id, - operator=operator, - value='', - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data( + field=self.cfield_str.id, + operator=operator, + value='', + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(self.cfield_str.id), condition.name) self.assertDictEqual( @@ -1840,14 +1795,13 @@ def test_equals_boolean_condition(self): model=FakeContact, efilter_registry=efilter_registry, ).clean operator = operators.EQUALS - conditions = clean(self.build_data( - field=self.cfield_bool.id, - operator=operator, - value=False, - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + clean(self.build_data( + field=self.cfield_bool.id, + operator=operator, + value=False, + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(self.cfield_bool.id), condition.name) self.assertDictEqual( @@ -1915,14 +1869,13 @@ def test_deleted02(self): operator = operators.ICONTAINS value = '[pilot]' - conditions = field.clean(self.build_data( - field=cfield_str.id, - operator=operator, - value=value, - )) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + field.clean(self.build_data( + field=cfield_str.id, + operator=operator, + value=value, + )) + ) self.assertEqual(CustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(cfield_str.id), condition.name) self.assertDictEqual( @@ -2111,12 +2064,11 @@ def test_deleted02(self): ], ) - conditions = field.clean(json_dump([ - {'field': str(cfield.id), 'range': {'type': 'current_year'}}, - ])) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + field.clean(json_dump([ + {'field': str(cfield.id), 'range': {'type': 'current_year'}}, + ])) + ) self.assertEqual(DateCustomFieldConditionHandler.type_id, condition.type) self.assertEqual(str(cfield.id), condition.name) @@ -2206,10 +2158,9 @@ def test_ok02(self): field = PropertiesConditionsField(efilter_type=EF_CREDENTIALS) field.model = FakeContact - conditions = field.clean(json_dump([{'ptype': ptype.id, 'has': True}])) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + field.clean(json_dump([{'ptype': ptype.id, 'has': True}])) + ) self.assertEqual(PropertyConditionHandler.type_id, condition.type) self.assertEqual(ptype.id, condition.name) self.assertEqual(EF_CREDENTIALS, condition.filter_type) @@ -2243,12 +2194,11 @@ def test_disabled_ptype02(self): ], ) - conditions = field.clean(json_dump([{'ptype': ptype.id, 'has': True}])) - self.assertEqual(1, len(conditions)) - - condition1 = conditions[0] - self.assertEqual(ptype.id, condition1.name) - self.assertIs(condition1.value, True) + condition = self.get_alone_element( + field.clean(json_dump([{'ptype': ptype.id, 'has': True}])) + ) + self.assertEqual(ptype.id, condition.name) + self.assertIs(condition.value, True) class RelationsConditionsFieldTestCase(FieldTestCase): @@ -2527,12 +2477,11 @@ def test_ok06(self): field.model = FakeContact rt_id = rtype.id - conditions = field.clean(json_dump([ - {'rtype': rt_id, 'has': True, 'ctype': 0, 'entity': None}, - ])) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + field.clean(json_dump([ + {'rtype': rt_id, 'has': True, 'ctype': 0, 'entity': None}, + ])) + ) self.assertEqual(RelationConditionHandler.type_id, condition.type) self.assertEqual(rt_id, condition.name) self.assertDictEqual({'has': True}, condition.value) @@ -2570,15 +2519,14 @@ def test_disabled_rtype02(self): ], ) - conditions = field.clean(json_dump([ - {'rtype': rtype.id, 'has': True, 'ctype': 0, 'entity': None}, - ])) - self.assertEqual(1, len(conditions)) - - condition1 = conditions[0] - self.assertEqual(RelationConditionHandler.type_id, condition1.type) - self.assertEqual(rtype.id, condition1.name) - self.assertDictEqual({'has': True}, condition1.value) + condition = self.get_alone_element( + field.clean(json_dump([ + {'rtype': rtype.id, 'has': True, 'ctype': 0, 'entity': None}, + ])) + ) + self.assertEqual(RelationConditionHandler.type_id, condition.type) + self.assertEqual(rtype.id, condition.name) + self.assertDictEqual({'has': True}, condition.value) def test_render_empty(self): widget = RelationsConditionsWidget() @@ -2707,23 +2655,19 @@ def test_filter_type(self): filter_id = self.sub_efilter01.id rt_id = rtype.id - conditions = field.clean(json_dump([ - { + condition = self.get_alone_element( + field.clean(json_dump([{ 'rtype': rt_id, 'has': True, 'ctype': ContentType.objects.get_for_model(FakeContact).id, 'filter': filter_id, - }, - ])) - self.assertEqual(1, len(conditions)) - - type_id = RelationSubFilterConditionHandler.type_id - condition1 = conditions[0] - self.assertEqual(type_id, condition1.type) - self.assertEqual(rt_id, condition1.name) - self.assertEqual(EF_CREDENTIALS, condition1.filter_type) + }])) + ) + self.assertEqual(RelationSubFilterConditionHandler.type_id, condition.type) + self.assertEqual(rt_id, condition.name) + self.assertEqual(EF_CREDENTIALS, condition.filter_type) self.assertDictEqual( {'has': True, 'filter_id': filter_id}, - condition1.value, + condition.value, ) def test_disabled_rtype01(self): @@ -2781,23 +2725,18 @@ def test_disabled_rtype02(self): ], ) filter_id = self.sub_efilter01.id - conditions = field.clean( - json_dump([ - { - 'rtype': rtype.id, 'has': True, - 'ctype': ContentType.objects.get_for_model(FakeContact).id, - 'filter': filter_id, - }, - ]), + condition = self.get_alone_element( + field.clean(json_dump([{ + 'rtype': rtype.id, 'has': True, + 'ctype': ContentType.objects.get_for_model(FakeContact).id, + 'filter': filter_id, + }])) ) - self.assertEqual(1, len(conditions)) - - condition1 = conditions[0] - self.assertEqual(RelationSubFilterConditionHandler.type_id, condition1.type) - self.assertEqual(rtype.id, condition1.name) + self.assertEqual(RelationSubFilterConditionHandler.type_id, condition.type) + self.assertEqual(rtype.id, condition.name) self.assertDictEqual( {'has': True, 'filter_id': filter_id}, - condition1.value, + condition.value, ) def test_render_empty(self): @@ -2867,10 +2806,7 @@ def test_creation_form01(self): self.assertIsNone(efilter.user, False) self.assertIs(efilter.is_private, False) - conditions = efilter.get_conditions() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.get_conditions()) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(fname, condition.name) self.assertDictEqual( @@ -2969,10 +2905,7 @@ def test_edition_form01(self): self.assertEqual(name, efilter_edited.name) self.assertIs(efilter_edited.use_or, True) - conditions = efilter.get_conditions() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.get_conditions()) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(fname, condition.name) self.assertDictEqual( diff --git a/creme/creme_core/tests/forms/test_fields.py b/creme/creme_core/tests/forms/test_fields.py index d4bcf876c0..9c2b27ef1a 100644 --- a/creme/creme_core/tests/forms/test_fields.py +++ b/creme/creme_core/tests/forms/test_fields.py @@ -84,10 +84,7 @@ def test_default(self): self.assertIsNone(field.initial) self.assertIsNone(field.user) - choices = [*field.choices] - self.assertEqual(1, len(choices)) - - active_group = choices[0] + active_group = self.get_alone_element(field.choices) self.assertEqual('', active_group[0]) active_choices = active_group[1] @@ -133,10 +130,7 @@ def test_queryset(self): field = CremeUserChoiceField(queryset=CremeUser.objects.exclude(is_staff=True)) - choices = [*field.choices] - self.assertEqual(1, len(choices)) - - active_group = choices[0] + active_group = self.get_alone_element(field.choices) self.assertEqual('', active_group[0]) active_choices = active_group[1] diff --git a/creme/creme_core/tests/forms/test_listview.py b/creme/creme_core/tests/forms/test_listview.py index 133e650251..6ac7a7f08a 100644 --- a/creme/creme_core/tests/forms/test_listview.py +++ b/creme/creme_core/tests/forms/test_listview.py @@ -720,9 +720,7 @@ def set_cfvalue(cfield, entity, value): self.assertIsInstance(q, Q) self.assertFalse(q.negated) - children = q.children - self.assertEqual(1, len(children)) - k, v = children[0] + k, v = self.get_alone_element(q.children) self.assertEqual('pk__in', k) self.assertSetEqual({ryu.id, ken.id}, {*v}) @@ -757,9 +755,7 @@ def set_cfvalue(cfield, entity, value): self.assertIsInstance(q_true, Q) self.assertFalse(q_true.negated) - children = q_true.children - self.assertEqual(1, len(children)) - k, v = children[0] + k, v = self.get_alone_element(q_true.children) self.assertEqual('pk__in', k) self.assertSetEqual({ryu.id, ken.id}, {*v}) @@ -805,9 +801,7 @@ def set_cfvalue(cfield, entity, value): self.assertIsInstance(q_equal, Q) self.assertFalse(q_equal.negated) - equal_children = q_equal.children - self.assertEqual(1, len(equal_children)) - equal_k, equal_v = equal_children[0] + equal_k, equal_v = self.get_alone_element(q_equal.children) self.assertEqual('pk__in', equal_k) self.assertListEqual([ken.id], [*equal_v]) @@ -876,9 +870,7 @@ def set_cfvalue(cfield, entity, value): self.assertIsInstance(q_equal, Q) self.assertFalse(q_equal.negated) - equal_children = q_equal.children - self.assertEqual(1, len(equal_children)) - equal_k, equal_v = equal_children[0] + equal_k, equal_v = self.get_alone_element(q_equal.children) self.assertEqual('pk__in', equal_k) self.assertListEqual([ken.id], [*equal_v]) @@ -952,9 +944,7 @@ def set_cfvalue(cfield, entity, value): self.assertIsInstance(q_range, Q) self.assertFalse(q_range.negated) - children = q_range.children - self.assertEqual(1, len(children)) - k, v = children[0] + k, v = self.get_alone_element(q_range.children) self.assertEqual('pk__in', k) self.assertSetEqual({ryu.id, ken.id}, {*v}) @@ -1029,9 +1019,7 @@ def set_cfvalue(entity, evalue): self.assertIsInstance(q_kick, Q) self.assertFalse(q_kick.negated) - children = q_kick.children - self.assertEqual(1, len(children)) - k, v = children[0] + k, v = self.get_alone_element(q_kick.children) self.assertEqual('pk__in', k) self.assertSetEqual({ryu.id, ken.id}, {*v}) @@ -1046,9 +1034,7 @@ def set_cfvalue(entity, evalue): self.assertIsInstance(q_null, Q) self.assertTrue(q_null.negated) - children = q_null.children - self.assertEqual(1, len(children)) - k, v = children[0] + k, v = self.get_alone_element(q_null.children) self.assertEqual('pk__in', k) self.assertSetEqual({ryu.id, ken.id, zangief.id}, {*v}) @@ -1102,9 +1088,7 @@ def set_cfvalue(entity, *evalues): self.assertIsInstance(q_kick, Q) self.assertFalse(q_kick.negated) - children = q_kick.children - self.assertEqual(1, len(children)) - k, v = children[0] + k, v = self.get_alone_element(q_kick.children) self.assertEqual('pk__in', k) self.assertSetEqual({ryu.id, ken.id}, {*v}) @@ -1119,9 +1103,7 @@ def set_cfvalue(entity, *evalues): self.assertIsInstance(q_null, Q) self.assertTrue(q_null.negated) - children = q_null.children - self.assertEqual(1, len(children)) - k, v = children[0] + k, v = self.get_alone_element(q_null.children) self.assertEqual('pk__in', k) self.assertSetEqual({ryu.id, ken.id, zangief.id}, {*v}) @@ -1160,9 +1142,7 @@ def test_relationfield(self): self.assertIsInstance(q, Q) self.assertFalse(q.negated) - children = q.children - self.assertEqual(1, len(children)) - k, v = children[0] + k, v = self.get_alone_element(q.children) self.assertEqual('pk__in', k) self.assertSetEqual({ryu.id, ken.id}, {*v}) diff --git a/creme/creme_core/tests/gui/test_actions.py b/creme/creme_core/tests/gui/test_actions.py index 5c32e789d3..320245efec 100644 --- a/creme/creme_core/tests/gui/test_actions.py +++ b/creme/creme_core/tests/gui/test_actions.py @@ -209,19 +209,13 @@ def test_action_is_registered_for_bulk02(self): registry.register_bulk_actions(MockBulkAction) # Entity --- - entity_actions = [*registry.bulk_actions(user, CremeEntity)] - self.assertEqual(1, len(entity_actions)) - - entity_action = entity_actions[0] + entity_action = self.get_alone_element(registry.bulk_actions(user, CremeEntity)) self.assertIsInstance(entity_action, MockBulkAction) self.assertEqual(user, entity_action.user) self.assertEqual(CremeEntity, entity_action.model) # Contact --- - contact_actions = [*registry.bulk_actions(user, FakeContact)] - self.assertEqual(1, len(contact_actions)) - - contact_action = contact_actions[0] + contact_action = self.get_alone_element(registry.bulk_actions(user, FakeContact)) self.assertIsInstance(contact_action, MockBulkAction) self.assertEqual(user, contact_action.user) self.assertEqual(FakeContact, contact_action.model) @@ -256,10 +250,9 @@ def test_action_is_registered_for_instance02(self): registry.register_instance_actions(MockAction) # Entity --- - entity_actions = [*registry.instance_actions(user=user, instance=entity)] - self.assertEqual(1, len(entity_actions)) - - entity_action = entity_actions[0] + entity_action = self.get_alone_element( + registry.instance_actions(user=user, instance=entity) + ) self.assertIsInstance(entity_action, MockAction) self.assertEqual(user, entity_action.user) self.assertEqual(CremeEntity, entity_action.model) @@ -270,10 +263,9 @@ def test_action_is_registered_for_instance02(self): ) # Contact --- - contact_actions = [*registry.instance_actions(user=user, instance=contact)] - self.assertEqual(1, len(contact_actions)) - - contact_action = contact_actions[0] + contact_action = self.get_alone_element( + registry.instance_actions(user=user, instance=contact) + ) self.assertIsInstance(contact_action, MockAction) self.assertEqual(user, contact_action.user) self.assertEqual(FakeContact, contact_action.model) diff --git a/creme/creme_core/tests/gui/test_bricks.py b/creme/creme_core/tests/gui/test_bricks.py index 2fe18dca67..e477b90ec2 100644 --- a/creme/creme_core/tests/gui/test_bricks.py +++ b/creme/creme_core/tests/gui/test_bricks.py @@ -540,10 +540,7 @@ def extract_model_brick(**kwargs): def test_get_compatible_hat_bricks01(self): brick_registry = _BrickRegistry() - bricks = [*brick_registry.get_compatible_hat_bricks(FakeContact)] - self.assertEqual(1, len(bricks)) - - brick = bricks[0] + brick = self.get_alone_element(brick_registry.get_compatible_hat_bricks(FakeContact)) self.assertIsInstance(brick, SimpleBrick) self.assertEqual((FakeContact,), brick.dependencies) self.assertEqual('creme_core/bricks/generic/hat-bar.html', brick.template_name) @@ -559,10 +556,9 @@ class FakeContactHatBrick(SimpleBrick): brick_registry = _BrickRegistry() brick_registry.register_hat(FakeContact, main_brick_cls=FakeContactHatBrick) - bricks = [*brick_registry.get_compatible_hat_bricks(FakeContact)] - self.assertEqual(1, len(bricks)) - - brick = bricks[0] + brick = self.get_alone_element( + brick_registry.get_compatible_hat_bricks(FakeContact) + ) self.assertIsInstance(brick, FakeContactHatBrick) self.assertEqual((FakeContact,), brick.dependencies) self.assertEqual(template, brick.template_name) @@ -695,9 +691,8 @@ def detailview_display(self, context): brick_registry = _BrickRegistry() brick_registry.register(FoobarBrick1, FoobarBrick2, FoobarBrick3) - blocks = [*brick_registry.get_compatible_home_bricks()] - self.assertEqual(1, len(blocks)) - self.assertIsInstance(blocks[0], FoobarBrick1) + brick = self.get_alone_element(brick_registry.get_compatible_home_bricks()) + self.assertIsInstance(brick, FoobarBrick1) def test_get_bricks01(self): class QuuxBrick1(SimpleBrick): @@ -731,13 +726,12 @@ def assertBricks(brick_classes, bricks): ) # Not registered ------------- - bricks = [ - *brick_registry.get_bricks([ + brick = self.get_alone_element( + brick_registry.get_bricks([ SimpleBrick.generate_id('creme_core', 'BrickRegistryTestCase__test_get_bricks_4'), ]) - ] - self.assertEqual(1, len(bricks)) - self.assertIsInstance(bricks[0], Brick) + ) + self.assertIsInstance(brick, Brick) def test_get_bricks02(self): "Model brick." @@ -828,25 +822,23 @@ class FakeContactCardHatBrick(SimpleBrick): self.assertFalse([*brick_registry.get_bricks([brick_id])]) # ---- - bricks = [*brick_registry.get_bricks([brick_id], entity=casca)] - self.assertEqual(1, len(bricks)) - self.assertIsInstance(bricks[0], FakeContactBasicHatBrick) + brick1 = self.get_alone_element(brick_registry.get_bricks([brick_id], entity=casca)) + self.assertIsInstance(brick1, FakeContactBasicHatBrick) # ---- - # bricks = [*brick_registry.get_bricks([FakeContactCardHatBrick.id_], entity=casca)] - bricks = [*brick_registry.get_bricks([FakeContactCardHatBrick.id], entity=casca)] - self.assertEqual(1, len(bricks)) - self.assertIsInstance(bricks[0], FakeContactCardHatBrick) + brick2 = self.get_alone_element( + brick_registry.get_bricks([FakeContactCardHatBrick.id], entity=casca) + ) + self.assertIsInstance(brick2, FakeContactCardHatBrick) # ---- - bricks = [ - *brick_registry.get_bricks( + brick3 = self.get_alone_element( + brick_registry.get_bricks( [SimpleBrick._generate_hat_id('creme_core', 'invalid')], entity=casca, - ), - ] - self.assertEqual(1, len(bricks)) - self.assertIsInstance(bricks[0], FakeContactBasicHatBrick) + ) + ) + self.assertIsInstance(brick3, FakeContactBasicHatBrick) def test_brick_4_model01(self): brick_registry = _BrickRegistry() @@ -919,21 +911,17 @@ def detailview_display(self, context): brick_registry.register_4_instance(ContactBrick) brick_id = ibci.brick_id - bricks = [*brick_registry.get_bricks([brick_id])] - self.assertEqual(1, len(bricks)) - - brick = bricks[0] - self.assertIsInstance(brick, ContactBrick) - self.assertEqual(ibci, brick.config_item) - # self.assertEqual(brick_id, brick.id_) - self.assertEqual(brick_id, brick.id) - self.assertEqual((FakeOrganisation,), brick.dependencies) + brick1 = self.get_alone_element(brick_registry.get_bricks([brick_id])) + self.assertIsInstance(brick1, ContactBrick) + self.assertEqual(ibci, brick1.config_item) + self.assertEqual(brick_id, brick1.id) + self.assertEqual((FakeOrganisation,), brick1.dependencies) # ---------------------------------------------------------------------- # In detail-views of an entity we give it in order to compute dependencies correctly. judo = create_contact(user=user, first_name='Judo', last_name='Doe') - brick = next(brick_registry.get_bricks([brick_id], entity=judo)) - self.assertEqual((FakeOrganisation, FakeContact), brick.dependencies) + brick2 = next(brick_registry.get_bricks([brick_id], entity=judo)) + self.assertEqual((FakeOrganisation, FakeContact), brick2.dependencies) hawk = FakeOrganisation.objects.create(user=user, name='Hawk') brick = next(brick_registry.get_bricks([brick_id], entity=hawk)) @@ -947,9 +935,8 @@ def detailview_display(self, context): 'does_not_exist', # <== ), ) - bricks = [*brick_registry.get_bricks([bad_ibci.brick_id])] - self.assertEqual(1, len(bricks)) - self.assertIsInstance(bricks[0], Brick) + brick3 = self.get_alone_element(brick_registry.get_bricks([bad_ibci.brick_id])) + self.assertIsInstance(brick3, Brick) def test_brick_4_instance02(self): self.login() diff --git a/creme/creme_core/tests/gui/test_custom_form.py b/creme/creme_core/tests/gui/test_custom_form.py index d87a32c206..89360e6f54 100644 --- a/creme/creme_core/tests/gui/test_custom_form.py +++ b/creme/creme_core/tests/gui/test_custom_form.py @@ -272,9 +272,8 @@ def test_from_cells01(self): self.assertIsInstance(fields_groups, FieldGroupList) self.assertEqual(FakeContact, fields_groups.model) self.assertIs(base_cell_registry, fields_groups.cell_registry) - self.assertEqual(1, len(fields_groups)) - group = fields_groups[0] + group = self.get_alone_element(fields_groups) self.assertIsInstance(group, FieldGroup) self.assertEqual(group_name, group.name) self.assertEqual(LAYOUT_REGULAR, group.layout) @@ -412,13 +411,13 @@ def test_from_cells_errors(self): ], cell_registry=base_cell_registry, ) - self.assertEqual(1, len(fields_groups)) - self.assertEqual(LAYOUT_REGULAR, fields_groups[0].layout) - messages = logs_manager.output - self.assertEqual(1, len(messages)) + fields_group = self.get_alone_element(fields_groups) + self.assertEqual(LAYOUT_REGULAR, fields_group.layout) + + message = self.get_alone_element(logs_manager.output) self.assertStartsWith( - messages[0], + message, 'WARNING:creme.creme_core.gui.custom_form:FieldGroupList.from_cells(): ' 'invalid layout "invalid" ', ) @@ -442,9 +441,8 @@ def test_from_dicts01(self): ) self.assertIsInstance(fields_groups, FieldGroupList) self.assertEqual(FakeContact, fields_groups.model) - self.assertEqual(1, len(fields_groups)) - group = fields_groups[0] + group = self.get_alone_element(fields_groups) self.assertIsInstance(group, FieldGroup) self.assertEqual(group_name, group.name) self.assertEqual(LAYOUT_REGULAR, group.layout) @@ -613,10 +611,7 @@ def test_form_regular_fields01(self): self.assertNotIn('relation_types', formfields1) self.assertNotIn('semifixed_rtypes', formfields1) - blocks = [*form1.get_blocks()] - self.assertEqual(1, len(blocks)) - - block = blocks[0] + block = self.get_alone_element(form1.get_blocks()) self.assertEqual(group_name, block.label) self.assertEqual(LAYOUT_REGULAR, block.layout) @@ -692,10 +687,7 @@ class MyFormBase(CremeEntityForm): self.assertNotIn('sector', fields) self.assertNotIn('address', fields) - blocks = [*form.get_blocks()] - self.assertEqual(1, len(blocks)) - - block = blocks[0] + block = self.get_alone_element(form.get_blocks()) self.assertEqual(group_name, block.label) self.assertEqual(LAYOUT_DUAL_FIRST, block.layout) self.assertListEqual(mfields, [bfield.name for bfield in block.bound_fields]) @@ -1099,10 +1091,9 @@ def test_form_custom_fields03(self): listified_blocks = [*form.get_blocks()] self.assertEqual(2, len(listified_blocks)) - block_fields = listified_blocks[1].bound_fields # Not cfield1.id - self.assertEqual(1, len(block_fields)) - self.assertEqual(f'custom_field-{cfield2.id}', block_fields[0].name) + block_field = self.get_alone_element(listified_blocks[1].bound_fields) + self.assertEqual(f'custom_field-{cfield2.id}', block_field.name) def test_form_custom_fields04(self): "Deleted missing required fields." @@ -1777,10 +1768,7 @@ class ExtraCells(EntityCellCustomFormExtra): self.assertEqual(label2, my_field2.label) self.assertIs(my_field2.required, False) - listified_blocks = [*form1.get_blocks()] - self.assertEqual(1, len(listified_blocks)) - - block_fields = listified_blocks[0].bound_fields + block_fields = self.get_alone_element(form1.get_blocks()).bound_fields self.assertEqual(4, len(block_fields)) self.assertEqual('user', block_fields[0].name) self.assertEqual('name', block_fields[1].name) @@ -2527,10 +2515,9 @@ def test_groups01(self): groups = form_desc.groups(item=cfci) self.assertIsInstance(groups, FieldGroupList) - self.assertEqual(1, len(groups)) self.assertEqual(FakeContact, groups.model) - group = groups[0] + group = self.get_alone_element(groups) self.assertEqual(group_name, group.name) self.assertEqual(LAYOUT_REGULAR, group.layout) self.assertListEqual( diff --git a/creme/creme_core/tests/gui/test_menu.py b/creme/creme_core/tests/gui/test_menu.py index cf633a551b..38b5d0a96c 100644 --- a/creme/creme_core/tests/gui/test_menu.py +++ b/creme/creme_core/tests/gui/test_menu.py @@ -777,10 +777,7 @@ def test_quick_forms_entries(self): registry = quick_forms.QuickFormsRegistry() seq.quickforms_registry = registry - entries1 = [*seq] - self.assertEqual(1, len(entries1)) - - entry11 = entries1[0] + entry11 = self.get_alone_element(seq) self.assertIsInstance(entry11, MenuEntry) self.assertEqual(_('No type available'), entry11.label) @@ -1473,18 +1470,17 @@ def test_registry03(self): "Container does not accept children." container_item = MenuConfigItem(id=1, entry_id=RecentEntitiesEntry.id) sub_item = MenuConfigItem( - id=2, entry_id=FakeContactsEntry.id, parent_id=container_item.id + id=2, entry_id=FakeContactsEntry.id, parent_id=container_item.id, ) registry = MenuRegistry().register( RecentEntitiesEntry, FakeContactsEntry ) - entries = registry.get_entries([container_item, sub_item]) - self.assertEqual(1, len(entries)) - - entry = entries[0] + entry = self.get_alone_element( + registry.get_entries([container_item, sub_item]) + ) self.assertIsInstance(entry, RecentEntitiesEntry) - self.assertListEqual([], [*entry.children]) + self.assertFalse([*entry.children]) def test_global_registry(self): entry_classes = {*menu_registry.entry_classes} diff --git a/creme/creme_core/tests/gui/test_misc.py b/creme/creme_core/tests/gui/test_misc.py index 2b02bbb74b..9fac898194 100644 --- a/creme/creme_core/tests/gui/test_misc.py +++ b/creme/creme_core/tests/gui/test_misc.py @@ -36,13 +36,11 @@ def test_last_viewed_items(self): class FakeRequest: def __init__(this): user_id = str(user.id) - sessions = [ + this.session = self.get_alone_element( d for d in (s.get_decoded() for s in Session.objects.all()) if d.get('_auth_user_id') == user_id - ] - self.assertEqual(1, len(sessions)) - this.session = sessions[0] + ) def get_items(): return LastViewedItem.get_all(FakeRequest()) @@ -60,6 +58,7 @@ def get_items(): self.assertEqual(1, len(items)) self.assertEqual(contact01.pk, items[0].pk) + # --- self.assertGET200(contact02.get_absolute_url()) self.assertGET200(contact03.get_absolute_url()) self.assertGET200(contact04.get_absolute_url()) @@ -67,23 +66,26 @@ def get_items(): self.assertEqual(4, len(items)) self.assertListEqual( [contact04.pk, contact03.pk, contact02.pk, contact01.pk], - [i.pk for i in items] + [i.pk for i in items], ) + # --- sleep(1) contact01.last_name = 'ILoveYou' contact01.save() self.assertGET200(FakeContact.get_lv_absolute_url()) old_item = get_items()[-1] - self.assertEqual(contact01.pk, old_item.pk) + self.assertEqual(contact01.pk, old_item.pk) self.assertEqual(str(contact01), old_item.name) + # --- self.assertGET200(contact02.get_absolute_url()) self.assertListEqual( [contact02.pk, contact04.pk, contact03.pk, contact01.pk], [i.pk for i in get_items()], ) + # --- contact03.delete() self.assertFalse(CremeEntity.objects.filter(pk=contact03.id)) self.assertGET200(FakeContact.get_lv_absolute_url()) @@ -93,6 +95,7 @@ def get_items(): [i.pk for i in items], ) + # --- contact04.trash() self.assertGET200(FakeContact.get_lv_absolute_url()) self.assertListEqual( @@ -116,10 +119,7 @@ def test_statistics01(self): fmt = 'There are {} Contacts'.format registry.register(s_id, label, lambda: [fmt(FakeContact.objects.count())]) - stats = [*registry] - self.assertEqual(1, len(stats)) - - stat = stats[0] + stat = self.get_alone_element(registry) self.assertEqual(s_id, stat.id) self.assertEqual(label, stat.label) self.assertListEqual([fmt(FakeContact.objects.count())], stat.retrieve()) diff --git a/creme/creme_core/tests/models/test_bricks.py b/creme/creme_core/tests/models/test_bricks.py index b69be5b01b..7e22bf9d69 100644 --- a/creme/creme_core/tests/models/test_bricks.py +++ b/creme/creme_core/tests/models/test_bricks.py @@ -148,13 +148,12 @@ def test_detail_manager_create_if_needed03(self): create_bdl(order=order, zone=zone) create_bdl(order=4, zone=BrickDetailviewLocation.LEFT) - locs = BrickDetailviewLocation.objects.filter( - brick_id=brick_id, - content_type=ContentType.objects.get_for_model(FakeContact), + loc = self.get_alone_element( + BrickDetailviewLocation.objects.filter( + brick_id=brick_id, + content_type=ContentType.objects.get_for_model(FakeContact), + ) ) - self.assertEqual(1, len(locs)) - - loc = locs[0] self.assertEqual(order, loc.order) self.assertEqual(zone, loc.zone) @@ -175,14 +174,13 @@ def test_detail_manager_create_if_needed04(self): create_bdl(order=order, zone=zone) create_bdl(order=4, zone=BrickDetailviewLocation.LEFT) - locs = BrickDetailviewLocation.objects.filter( - brick_id=brick_id, - content_type=ctype, - role=role, superuser=False, + loc = self.get_alone_element( + BrickDetailviewLocation.objects.filter( + brick_id=brick_id, + content_type=ctype, + role=role, superuser=False, + ) ) - self.assertEqual(1, len(locs)) - - loc = locs[0] self.assertEqual(order, loc.order) self.assertEqual(zone, loc.zone) @@ -208,15 +206,14 @@ def test_detail_manager_create_if_needed05(self): create_bdl(order=order, zone=zone) create_bdl(order=4, zone=BrickDetailviewLocation.LEFT) - locs = BrickDetailviewLocation.objects.filter( - # brick_id=MyBrick.id_, - brick_id=MyBrick.id, - content_type=ContentType.objects.get_for_model(FakeContact), - role=None, superuser=True, + loc = self.get_alone_element( + BrickDetailviewLocation.objects.filter( + # brick_id=MyBrick.id_, + brick_id=MyBrick.id, + content_type=ContentType.objects.get_for_model(FakeContact), + role=None, superuser=True, + ) ) - self.assertEqual(1, len(locs)) - - loc = locs[0] self.assertEqual(order, loc.order) self.assertEqual(zone, loc.zone) @@ -632,9 +629,8 @@ def test_relation_brick_errors(self): rbi.save() rbi = self.refresh(rbi) - cells_contact = rbi.get_cells(ct_contact) - self.assertEqual(1, len(cells_contact)) - self.assertEqual('last_name', cells_contact[0].value) + cell_contact = self.get_alone_element(rbi.get_cells(ct_contact)) + self.assertEqual('last_name', cell_contact.value) with self.assertNoException(): deserialized = rbi.json_cells_map @@ -734,10 +730,7 @@ def test_custom_brick(self): ) self.assertEqual(f'customblock-{cbci.id}', cbci.brick_id) - cells = self.refresh(cbci).cells - self.assertEqual(1, len(cells)) - - cell = cells[0] + cell = self.get_alone_element(self.refresh(cbci).cells) self.assertIsInstance(cell, EntityCellRegularField) self.assertEqual('name', cell.value) diff --git a/creme/creme_core/tests/models/test_entity_filter.py b/creme/creme_core/tests/models/test_entity_filter.py index 4683f00a60..51ad40487a 100644 --- a/creme/creme_core/tests/models/test_entity_filter.py +++ b/creme/creme_core/tests/models/test_entity_filter.py @@ -184,10 +184,7 @@ def test_manager_smart_update_or_create01(self): self.assertEqual(entity_filter_registries[EF_USER], efilter.registry) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(fname, condition.name) self.assertEqual( @@ -451,10 +448,7 @@ def test_manager_smart_update_or_create_again01(self): self.assertEqual(user, efilter.user) self.assertFalse(efilter.use_or) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual('first_name', condition.name) self.assertEqual( @@ -675,9 +669,7 @@ def test_filter_field_equals01(self): with self.assertNumQueries(0): conds = efilter.get_conditions() - self.assertEqual(1, len(conds)) - - cond = conds[0] + cond = self.get_alone_element(conds) self.assertIsInstance(cond, EntityFilterCondition) self.assertEqual('last_name', cond.name) @@ -1549,19 +1541,14 @@ def test_set_conditions01(self): build(operator=operators.EQUALS, field_name='first_name', values=['Faye']), ]) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - old_id = conditions[0].id + old_id = self.get_alone_element(efilter.conditions.all()).id operator = operators.CONTAINS name = 'last_name' value = 'Black' efilter.set_conditions([build(operator=operator, field_name=name, values=[value])]) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = efilter.conditions.all(efilter.conditions.all()) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(name, condition.name) self.assertEqual(old_id, condition.id) @@ -1610,10 +1597,7 @@ def test_set_conditions02(self): kwargs1['operator'] = operators.GT efilter.set_conditions([build(**kwargs1)]) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = efilter.conditions.all(efilter.conditions.all()) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(kwargs1['field_name'], condition.name) self.assertEqual(old_id, condition.id) @@ -1643,10 +1627,7 @@ def test_set_conditions03(self): ]) self.assertFalse(efilter.get_conditions()) - conditions = [*efilter.conditions.all()] - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual(SubFilterConditionHandler.type_id, condition.type) self.assertEqual('invalid_id', condition.name) @@ -1708,18 +1689,16 @@ def test_get_conditions_errors(self): efilter = EntityFilter.objects.smart_update_or_create( pk='test-filter01', name='Test', model=FakeContact, is_custom=True, ) - condition = RegularFieldConditionHandler.build_condition( + condition1 = RegularFieldConditionHandler.build_condition( model=FakeContact, operator=operators.EQUALS, field_name='last_name', values=['Ikari'], ) - condition.filter = efilter - condition.save() - - conditions = self.refresh(efilter).get_conditions() - self.assertEqual(1, len(conditions)) + condition1.filter = efilter + condition1.save() - EntityFilterCondition.objects.filter(id=conditions[0].id).update(raw_value='[]') + condition2 = self.get_alone_element(self.refresh(efilter).get_conditions()) + EntityFilterCondition.objects.filter(id=condition2.id).update(raw_value='[]') self.assertFalse(self.refresh(efilter).get_conditions()) def test_multi_conditions_and01(self): diff --git a/creme/creme_core/tests/models/test_file_ref.py b/creme/creme_core/tests/models/test_file_ref.py index bde28c275d..3f138e93b4 100644 --- a/creme/creme_core/tests/models/test_file_ref.py +++ b/creme/creme_core/tests/models/test_file_ref.py @@ -137,10 +137,7 @@ def test_create_at_deletion01(self): doc.delete() self.assertDoesNotExist(doc) - file_refs = FileRef.objects.exclude(id__in=existing_ids) - self.assertEqual(1, len(file_refs)) - - file_ref = file_refs[0] + file_ref = self.get_alone_element(FileRef.objects.exclude(id__in=existing_ids)) self.assertTrue(file_ref.temporary) self.assertIsNone(file_ref.user) self.assertEqual(full_path, file_ref.filedata.path) @@ -176,10 +173,7 @@ def test_delete_model_with_file01(self): self.assertDoesNotExist(doc) - file_refs = FileRef.objects.exclude(id__in=existing_ids) - self.assertEqual(1, len(file_refs)) - - file_ref = file_refs[0] + file_ref = self.get_alone_element(FileRef.objects.exclude(id__in=existing_ids)) self.assertTrue(file_ref.temporary) self.assertIsNone(file_ref.user) self.assertEqual(full_path, file_ref.filedata.path) diff --git a/creme/creme_core/tests/models/test_history.py b/creme/creme_core/tests/models/test_history.py index c6f799d7ad..446aeace2e 100644 --- a/creme/creme_core/tests/models/test_history.py +++ b/creme/creme_core/tests/models/test_history.py @@ -1541,9 +1541,10 @@ def test_multi_save01(self): rei.last_name = new_last_name rei.save() - hlines = [*HistoryLine.objects.filter(entity=rei.id).order_by('id')] - self.assertEqual(1, len(hlines)) - self.assertEqual(TYPE_CREATION, hlines[0].type) + hline = self.get_alone_element( + HistoryLine.objects.filter(entity=rei.id).order_by('id') + ) + self.assertEqual(TYPE_CREATION, hline.type) def test_multi_save02(self): "Beware: internal backup must be recreated after the save()." @@ -1752,9 +1753,8 @@ def test_delete_lines(self): HistoryLine.delete_lines(hayao_line_qs) self.assertFalse(hayao_line_qs.all()) - ghibli_lines = [*ghibli_line_qs.all()] - self.assertEqual(1, len(ghibli_lines)) - self.assertEqual(TYPE_CREATION, ghibli_lines[0].type) + ghibli_line = self.get_alone_element(ghibli_line_qs.all()) + self.assertEqual(TYPE_CREATION, ghibli_line.type) def test_populate_users01(self): user = self.user diff --git a/creme/creme_core/tests/models/test_search.py b/creme/creme_core/tests/models/test_search.py index b4c24ea6c6..ae249d8bbd 100644 --- a/creme/creme_core/tests/models/test_search.py +++ b/creme/creme_core/tests/models/test_search.py @@ -21,10 +21,7 @@ def test_manager_create_if_needed01(self): ) self.assertEqual(count + 1, SearchConfigItem.objects.count()) - sc_items = SearchConfigItem.objects.filter(content_type=ct) - self.assertEqual(1, len(sc_items)) - - sc_item = sc_items[0] + sc_item = self.get_alone_element(SearchConfigItem.objects.filter(content_type=ct)) self.assertEqual(FakeContact, sc_item.content_type.model_class()) self.assertIsNone(sc_item.role) self.assertIs(sc_item.superuser, False) @@ -101,9 +98,8 @@ def test_manager_create_if_needed04(self): FakeContact, ['invalid_field', 'first_name'], ) - cells = [*sc_item.cells] - self.assertEqual(1, len(cells)) - self.assertEqual('first_name', cells[0].value) + cell = self.get_alone_element(sc_item.cells) + self.assertEqual('first_name', cell.value) def test_manager_create_if_needed05(self): "Invalid fields : no subfield." @@ -111,9 +107,8 @@ def test_manager_create_if_needed05(self): FakeContact, ['last_name__invalid', 'first_name'], ) - cells = [*sc_item.cells] - self.assertEqual(1, len(cells)) - self.assertEqual('first_name', cells[0].value) + cell = self.get_alone_element(sc_item.cells) + self.assertEqual('first_name', cell.value) def test_manager_create_if_needed06(self): "Disabled." @@ -278,13 +273,14 @@ def test_manager_get_for_models03(self): "One model, 1 config in DB." user = self.create_user() - sc_item = SearchConfigItem.objects.create_if_needed( + created_item = SearchConfigItem.objects.create_if_needed( FakeContact, ['first_name', 'last_name'], ) - configs = [*SearchConfigItem.objects.iter_for_models([FakeContact], user)] - self.assertEqual(1, len(configs)) - self.assertEqual(sc_item, configs[0]) + retrieved_item = self.get_alone_element( + SearchConfigItem.objects.iter_for_models([FakeContact], user) + ) + self.assertEqual(created_item, retrieved_item) def test_manager_get_for_models04(self): "One model, 2 configs in DB." @@ -298,12 +294,13 @@ def test_manager_get_for_models04(self): create(FakeContact, ['description'], role='superuser') create(FakeContact, ['first_name', 'last_name']) create(FakeContact, ['first_name'], role=role2) - sc_item = create(FakeContact, ['last_name'], role=self.role) # <=== + created_item = create(FakeContact, ['last_name'], role=self.role) # <=== create(FakeContact, ['first_name', 'description'], role=role3) - configs = [*SearchConfigItem.objects.iter_for_models([FakeContact], self.other_user)] - self.assertEqual(1, len(configs)) - self.assertEqual(sc_item, configs[0]) + retrieved_item = self.get_alone_element( + SearchConfigItem.objects.iter_for_models([FakeContact], self.other_user) + ) + self.assertEqual(created_item, retrieved_item) def test_manager_get_for_models05(self): "One model, 2 configs in DB (other order)." diff --git a/creme/creme_core/tests/models/test_setting_value.py b/creme/creme_core/tests/models/test_setting_value.py index 5c33900bb8..977b87adeb 100644 --- a/creme/creme_core/tests/models/test_setting_value.py +++ b/creme/creme_core/tests/models/test_setting_value.py @@ -256,9 +256,8 @@ def test_get_4_key03(self): with self.assertRaises(SettingValue.DoesNotExist): SettingValue.objects.get_4_key(sk) - messages = log_cm.output - self.assertEqual(1, len(messages)) - self.assertIn(''"creme_populate"'', messages[0]) + message = self.get_alone_element(log_cm.output) + self.assertIn(''"creme_populate"'', message) def test_get_4_key04(self): "Default value." @@ -270,9 +269,8 @@ def test_get_4_key04(self): with self.assertLogs(level='CRITICAL') as log_cm: sv = SettingValue.objects.get_4_key(sk, default=False) - messages = log_cm.output - self.assertEqual(1, len(messages)) - self.assertIn('creme_populate', messages[0]) + message = self.get_alone_element(log_cm.output) + self.assertIn('creme_populate', message) self.assertEqual(sk.id, sv.key_id) self.assertIs(False, sv.value) @@ -342,9 +340,8 @@ def test_get_4_keys02(self): with self.assertRaises(SettingValue.DoesNotExist): SettingValue.objects.get_4_keys({'key': sk}) - messages = log_cm.output - self.assertEqual(1, len(messages)) - self.assertIn(''"creme_populate"'', messages[0]) + message = self.get_alone_element(log_cm.output) + self.assertIn(''"creme_populate"'', message) def test_get_4_keys03(self): "Default value." @@ -356,9 +353,8 @@ def test_get_4_keys03(self): with self.assertLogs(level='CRITICAL') as log_cm: svalues = SettingValue.objects.get_4_keys({'key': sk, 'default': False}) - messages = log_cm.output - self.assertEqual(1, len(messages)) - self.assertIn('creme_populate', messages[0]) + message = self.get_alone_element(log_cm.output) + self.assertIn('creme_populate', message) sv = svalues.get(sk.id) self.assertEqual(sk.id, sv.key_id) diff --git a/creme/creme_core/tests/test_backends.py b/creme/creme_core/tests/test_backends.py index 7c8180fe39..ed7693016f 100644 --- a/creme/creme_core/tests/test_backends.py +++ b/creme/creme_core/tests/test_backends.py @@ -41,10 +41,9 @@ def test_registration_errors02(self): self.assertIsNone(backend) - messages = log_cm.output - self.assertEqual(1, len(messages)) + message = self.get_alone_element(log_cm.output) self.assertStartsWith( - messages[0], + message, f'WARNING:creme.creme_core.utils.imports:' f'An error occurred trying to import "{path}":' ) diff --git a/creme/creme_core/tests/test_base_test_case.py b/creme/creme_core/tests/test_base_test_case.py index 633dcd5fac..6aade457b5 100644 --- a/creme/creme_core/tests/test_base_test_case.py +++ b/creme/creme_core/tests/test_base_test_case.py @@ -492,6 +492,40 @@ def test_assertEndsWith(self): str(cm.exception), ) + def test_get_alone_element(self): + with self.assertNoException(): + e1 = self.get_alone_element([1]) + self.assertEqual(1, e1) + + # Other value returned --- + with self.assertNoException(): + e2 = self.get_alone_element(['2']) + self.assertEqual('2', e2) + + # Failure with list + length==2 --- + with self.assertRaises(self.failureException) as cm1: + self.get_alone_element([1, 2]) + self.assertEqual( + 'The iterable has 2 elements, not 1', + str(cm1.exception), + ) + + # Failure with range() + length==3 --- + with self.assertRaises(self.failureException) as cm2: + self.get_alone_element(range(1, 4)) + self.assertEqual( + 'The iterable has 3 elements, not 1', + str(cm2.exception), + ) + + # Failure with generator --- + with self.assertRaises(self.failureException) as cm3: + self.get_alone_element(i * i for i in range(3)) + self.assertEqual( + 'The iterable has 3 elements, not 1', + str(cm3.exception), + ) + def test_get_object_or_fail(self): sector1 = FakeSector.objects.create(title='Catch me') diff --git a/creme/creme_core/tests/utils/test_chunktools.py b/creme/creme_core/tests/utils/test_chunktools.py index 97e1cc744a..3451e562e7 100644 --- a/creme/creme_core/tests/utils/test_chunktools.py +++ b/creme/creme_core/tests/utils/test_chunktools.py @@ -82,9 +82,8 @@ def test_iter_as_slices03(self): self.assertEqual(data, ''.join(chunks)) def test_iter_as_chunks01(self): - chunks = [*chunktools.iter_as_chunk(self.DATA_UNIX, 1000)] - self.assertEqual(1, len(chunks)) - self.assertEqual(self.DATA_UNIX, ''.join(chunks[0])) + chunk = self.get_alone_element(chunktools.iter_as_chunk(self.DATA_UNIX, 1000)) + self.assertEqual(self.DATA_UNIX, ''.join(chunk)) def test_iter_as_chunks02(self): assert len(self.DATA_UNIX) % 5 == 0 diff --git a/creme/creme_core/tests/utils/test_meta.py b/creme/creme_core/tests/utils/test_meta.py index 981101cc05..a78726c0b8 100644 --- a/creme/creme_core/tests/utils/test_meta.py +++ b/creme/creme_core/tests/utils/test_meta.py @@ -54,7 +54,7 @@ def test_orderedfield_desc(self): class FieldInfoTestCase(CremeTestCase): def test_field_info01(self): - "Simple field" + "Simple field." fi = meta.FieldInfo(FakeContact, 'first_name') self.assertEqual(FakeContact, fi.model) @@ -150,8 +150,8 @@ def test_field_info_slice03(self): User = get_user_model() self.assertEqual(User, sub_fi.model) - self.assertEqual(1, len(sub_fi)) - self.assertEqual(User._meta.get_field('username'), sub_fi[0]) + sub_field = self.get_alone_element(sub_fi) + self.assertEqual(User._meta.get_field('username'), sub_field) def test_field_info_slice04(self): "'very' negative start." diff --git a/creme/creme_core/tests/utils/test_xls_utils.py b/creme/creme_core/tests/utils/test_xls_utils.py index d524302767..a8ef6f4df0 100644 --- a/creme/creme_core/tests/utils/test_xls_utils.py +++ b/creme/creme_core/tests/utils/test_xls_utils.py @@ -103,9 +103,6 @@ def test_truncate(self): with self.assertNoException(): wt.save(file.name) - read_content = [*XlrdReader(filedata=file.name)] - self.assertEqual(1, len(read_content)) - - elt = read_content[0] - self.assertEqual(1, len(elt)) - self.assertEqual(32767, len(elt[0])) + row = self.get_alone_element(XlrdReader(filedata=file.name)) + elt = self.get_alone_element(row) + self.assertEqual(32767, len(elt)) diff --git a/creme/creme_core/tests/views/entity/test_bulk_update.py b/creme/creme_core/tests/views/entity/test_bulk_update.py index 9f68c3fd8d..dcac1ec1c9 100644 --- a/creme/creme_core/tests/views/entity/test_bulk_update.py +++ b/creme/creme_core/tests/views/entity/test_bulk_update.py @@ -124,11 +124,12 @@ def test_no_field_given(self): choices_f = fields['_bulk_fieldname'] choices = choices_f.choices - other_fields = [name for name in fields.keys() if name != '_bulk_fieldname'] - self.assertEqual(1, len(other_fields)) + other_field = self.get_alone_element( + name for name in fields.keys() if name != '_bulk_fieldname' + ) with self.assertNoException(): - FakeContact._meta.get_field(other_fields[0]) + FakeContact._meta.get_field(other_field) build_url = partial(self.build_bulkupdate_uri, model=FakeContact) self.assertInChoices( @@ -137,7 +138,7 @@ def test_no_field_given(self): self.assertInChoices( value=build_url(field='user'), label=_('Owner user'), choices=choices, ) - self.assertEqual(build_url(field=other_fields[0]), choices_f.initial) + self.assertEqual(build_url(field=other_field), choices_f.initial) def test_regular_field_not_entity_model(self): self.login() diff --git a/creme/creme_core/tests/views/entity/test_deletion.py b/creme/creme_core/tests/views/entity/test_deletion.py index d6221e116c..14627758af 100644 --- a/creme/creme_core/tests/views/entity/test_deletion.py +++ b/creme/creme_core/tests/views/entity/test_deletion.py @@ -662,10 +662,7 @@ def test_empty_trash01(self): response = self.assertPOST200(url) self.assertTemplateUsed(response, 'creme_core/job/trash-cleaning-popup.html') - jobs = Job.objects.filter(type_id=trash_cleaner_type.id) - self.assertEqual(1, len(jobs)) - - job = jobs[0] + job = self.get_alone_element(Job.objects.filter(type_id=trash_cleaner_type.id)) self.assertEqual(self.user, job.user) self.assertEqual(Job.STATUS_WAIT, job.status) self.assertIsNone(job.error) @@ -761,9 +758,8 @@ def test_empty_trash02(self): self.assertIn(entity02.id, jresults) - result_bricks = trash_cleaner_type.results_bricks - self.assertEqual(1, len(result_bricks)) - self.assertIsInstance(result_bricks[0], EntityJobErrorsBrick) + result_brick = self.get_alone_element(trash_cleaner_type.results_bricks) + self.assertIsInstance(result_brick, EntityJobErrorsBrick) @override_settings(ENTITIES_DELETION_ALLOWED=True) def test_empty_trash03(self): diff --git a/creme/creme_core/tests/views/test_auth.py b/creme/creme_core/tests/views/test_auth.py index 56a5fd415e..feb46958e8 100644 --- a/creme/creme_core/tests/views/test_auth.py +++ b/creme/creme_core/tests/views/test_auth.py @@ -38,10 +38,7 @@ def test_reset_password01(self): self.assertTemplateUsed(response2, 'creme_core/auth/password_reset/done.html') self.assertEqual(_('Reset your password (Step 2/4)'), response2.context.get('title')) - messages = mail.outbox - self.assertEqual(1, len(messages)) - - message = messages[0] + message = self.get_alone_element(mail.outbox) self.assertListEqual([user.email], message.recipients()) self.assertEqual('admin@mycompagny.org', message.from_email) self.assertListEqual([], message.alternatives) diff --git a/creme/creme_core/tests/views/test_batch_process.py b/creme/creme_core/tests/views/test_batch_process.py index bb1856bd67..d0b1f36c9c 100644 --- a/creme/creme_core/tests/views/test_batch_process.py +++ b/creme/creme_core/tests/views/test_batch_process.py @@ -130,10 +130,7 @@ def test_batching_upper01(self): ) self.assertNoFormError(response) - jobs = Job.objects.filter(type_id=batch_process_type.id) - self.assertEqual(1, len(jobs)) - - job = jobs[0] + job = self.get_alone_element(Job.objects.filter(type_id=batch_process_type.id)) self.assertEqual(self.user, job.user) self.assertDatetimesAlmostEqual(now(), job.reference_run, 1) self.assertIsInstance(job.data, dict) diff --git a/creme/creme_core/tests/views/test_bricks.py b/creme/creme_core/tests/views/test_bricks.py index 34226e5a67..cab3d1e818 100644 --- a/creme/creme_core/tests/views/test_bricks.py +++ b/creme/creme_core/tests/views/test_bricks.py @@ -128,13 +128,12 @@ def test_set_state03(self): ) bstates = BrickState.objects.filter(brick_id=brick_id) - user_bstates = [bstate for bstate in bstates if bstate.user == user] - other_bstates = [bstate for bstate in bstates if bstate.user == other_user] - - self.assertEqual(1, len(user_bstates)) - self.assertEqual(1, len(other_bstates)) - user_bstate = user_bstates[0] - other_bstate = other_bstates[0] + user_bstate = self.get_alone_element( + bstate for bstate in bstates if bstate.user == user + ) + other_bstate = self.get_alone_element( + bstate for bstate in bstates if bstate.user == other_user + ) self.assertTrue(other_bstate.is_open) self.assertTrue(other_bstate.show_empty_fields) diff --git a/creme/creme_core/tests/views/test_creme_property.py b/creme/creme_core/tests/views/test_creme_property.py index c26ce19952..e41b150175 100644 --- a/creme/creme_core/tests/views/test_creme_property.py +++ b/creme/creme_core/tests/views/test_creme_property.py @@ -702,7 +702,7 @@ def test_reload_ptype_bricks02(self): self.get_brick_node(doc2, info_brick_id) def test_reload_ptype_bricks03(self): - "Empty block." + "Empty brick." self.login() ptype = CremePropertyType.objects.smart_update_or_create( str_pk='test-prop_murica', text='is american', @@ -719,7 +719,7 @@ def test_reload_ptype_bricks03(self): with self.assertNoException(): result = response.json() - self.assertEqual(1, len(result)) - doc = self.get_html_tree(result[0][1]) + brick_data = self.get_alone_element(result) + doc = self.get_html_tree(brick_data[1]) brick_node = self.get_brick_node(doc, brick_id) self.assertBrickHasClass(brick_node, 'is-empty') diff --git a/creme/creme_core/tests/views/test_entity_filter.py b/creme/creme_core/tests/views/test_entity_filter.py index cab0cc8daa..753229b3a2 100644 --- a/creme/creme_core/tests/views/test_entity_filter.py +++ b/creme/creme_core/tests/views/test_entity_filter.py @@ -166,20 +166,14 @@ def test_create01(self): ) self.assertNoFormError(response) - efilters = EntityFilter.objects.filter(entity_type=ct) - self.assertEqual(1, len(efilters)) - - efilter = efilters[0] + efilter = self.get_alone_element(EntityFilter.objects.filter(entity_type=ct)) self.assertEqual(name, efilter.name) self.assertTrue(efilter.is_custom) self.assertFalse(efilter.is_private) self.assertIsNone(efilter.user) self.assertFalse(efilter.use_or) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(field_name, condition.name) self.assertDictEqual( @@ -436,10 +430,7 @@ def test_create04(self): efilter = self.get_object_or_fail(EntityFilter, entity_type=ct, name=name) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual(DateRegularFieldConditionHandler.type_id, condition.type) self.assertEqual(field_name, condition.name) self.assertDictEqual({'name': daterange_type}, condition.value) @@ -625,11 +616,7 @@ def test_create_creatorfield_fk_filter(self): self.assertNoFormError(response, status=302) efilter = self.get_object_or_fail(EntityFilter, name='Filter 01') - conditions = efilter.conditions.all() - - self.assertEqual(1, len(conditions)) - condition = conditions[0] - + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual('linked_folder', condition.name) self.assertDictEqual( @@ -663,11 +650,7 @@ def test_create_currentuser_filter(self): self.assertEqual(user.id, efilter.user.id) self.assertIs(efilter.use_or, True) - conditions = efilter.conditions.all() - self.assertEqual(1, len(conditions)) - iter_conds = iter(conditions) - - condition = next(iter_conds) + condition = self.get_alone_element(efilter.conditions.all()) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual('user', condition.name) self.assertDictEqual( @@ -1223,10 +1206,7 @@ def test_edit02(self): self.assertFalse(efilter.is_custom) self.assertEqual(self.user, efilter.user) - conditions = efilter.conditions.order_by('id') - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(efilter.conditions.order_by('id')) self.assertEqual(RegularFieldConditionHandler.type_id, condition.type) self.assertEqual(field_name, condition.name) self.assertDictEqual( diff --git a/creme/creme_core/tests/views/test_enumerable.py b/creme/creme_core/tests/views/test_enumerable.py index 1123649599..18a59ea573 100644 --- a/creme/creme_core/tests/views/test_enumerable.py +++ b/creme/creme_core/tests/views/test_enumerable.py @@ -155,9 +155,9 @@ def test_choices_success_specific_printer01(self): self.assertIn('value', first_choice) def find_efilter_dict(efilter): - efilter_as_dicts = [c for c in choices if c['value'] == efilter.id] - self.assertEqual(1, len(efilter_as_dicts)) - return efilter_as_dicts[0] + return self.get_alone_element( + c for c in choices if c['value'] == efilter.id + ) self.assertDictEqual( { @@ -191,9 +191,7 @@ def test_choices_success_specific_printer02(self): def find_ctype_label(model): ctype_id = get_ct(model).id - ctype_as_lists = [t for t in choices if t['value'] == ctype_id] - self.assertEqual(1, len(ctype_as_lists)) - choice = ctype_as_lists[0] + choice = self.get_alone_element(t for t in choices if t['value'] == ctype_id) self.assertEqual(2, len(choice)) return choice['label'] diff --git a/creme/creme_core/tests/views/test_generic.py b/creme/creme_core/tests/views/test_generic.py index 9a542aab4e..ed34ddba4c 100644 --- a/creme/creme_core/tests/views/test_generic.py +++ b/creme/creme_core/tests/views/test_generic.py @@ -83,19 +83,15 @@ def test_basic(self): self.assertIsNone(response.context['visitor']) # ----- - last_items = LastViewedItem.get_all(self.FakeRequest(user)) - self.assertEqual(1, len(last_items)) - - last_item = last_items[0] + last_item = self.get_alone_element(LastViewedItem.get_all(self.FakeRequest(user))) self.assertEqual(fox.id, last_item.pk) self.assertEqual(fox.entity_type_id, last_item.ctype_id) self.assertEqual(url, last_item.url) self.assertEqual(str(fox), last_item.name) # ----- - imprints = Imprint.objects.all() - self.assertEqual(1, len(imprints)) - self.assertEqual(imprints[0].entity.get_real_entity(), fox) + imprint = self.get_alone_element(Imprint.objects.all()) + self.assertEqual(imprint.entity.get_real_entity(), fox) # ----- tree = self.get_html_tree(response.content) diff --git a/creme/creme_core/tests/views/test_header_filter.py b/creme/creme_core/tests/views/test_header_filter.py index 08c9edfc78..633a28d8cd 100644 --- a/creme/creme_core/tests/views/test_header_filter.py +++ b/creme/creme_core/tests/views/test_header_filter.py @@ -74,10 +74,7 @@ def test_create01(self): ) self.assertNoFormError(response, status=302) - hfilters = HeaderFilter.objects.filter(entity_type=ct) - self.assertEqual(1, len(hfilters)) - - hfilter = hfilters[0] + hfilter = self.get_alone_element(HeaderFilter.objects.filter(entity_type=ct)) self.assertEqual(name, hfilter.name) self.assertIsNone(hfilter.user) self.assertTrue(hfilter.is_custom) diff --git a/creme/creme_core/tests/views/test_imprint.py b/creme/creme_core/tests/views/test_imprint.py index 5635ef70c7..85fe37e1a8 100644 --- a/creme/creme_core/tests/views/test_imprint.py +++ b/creme/creme_core/tests/views/test_imprint.py @@ -33,10 +33,7 @@ def test_detailview(self): self.assertGET200(orga.get_absolute_url()) - imprints = Imprint.objects.all() - self.assertEqual(1, len(imprints)) - - imprint = imprints[0] + imprint = self.get_alone_element(Imprint.objects.all()) self.assertDatetimesAlmostEqual(now(), imprint.date) self.assertEqual(imprint.entity.get_real_entity(), orga) self.assertEqual(imprint.user, user) @@ -51,10 +48,7 @@ def test_granularity01(self): self.assertGET200(orga.get_absolute_url()) self.assertGET200(orga.get_absolute_url()) - imprints = Imprint.objects.all() - self.assertEqual(1, len(imprints)) # not 2 - - imprint = imprints[0] + imprint = self.get_alone_element(Imprint.objects.all()) # not 2 self.assertDatetimesAlmostEqual(now(), imprint.date) self.assertEqual(imprint.entity.get_real_entity(), orga) self.assertEqual(imprint.user, user) diff --git a/creme/creme_core/tests/views/test_mass_export.py b/creme/creme_core/tests/views/test_mass_export.py index 63873d98af..36252febcd 100644 --- a/creme/creme_core/tests/views/test_mass_export.py +++ b/creme/creme_core/tests/views/test_mass_export.py @@ -260,9 +260,10 @@ def test_xls_export_header(self): follow=True, ) - result = [*XlrdReader(None, file_contents=b''.join(response.streaming_content))] - self.assertEqual(1, len(result)) - self.assertEqual(result[0], [hfi.title for hfi in cells]) + result = self.get_alone_element( + XlrdReader(None, file_contents=b''.join(response.streaming_content)) + ) + self.assertListEqual([hfi.title for hfi in cells], result) def test_list_view_export_csv(self): user = self.login() @@ -283,10 +284,7 @@ def test_list_view_export_csv(self): next(it) # History - hlines = HistoryLine.objects.exclude(id__in=existing_hline_ids) - self.assertEqual(1, len(hlines)) - - hline = hlines[0] + hline = self.get_alone_element(HistoryLine.objects.exclude(id__in=existing_hline_ids)) self.assertEqual(self.ct, hline.entity_ctype) self.assertEqual(user, hline.entity_owner) self.assertEqual(TYPE_EXPORT, hline.type) @@ -532,10 +530,7 @@ def test_list_view_export_with_filter01(self): self.assertEqual('"","Wong","Edward","","is a girl"', result[1]) # History - hlines = HistoryLine.objects.exclude(id__in=existing_hline_ids) - self.assertEqual(1, len(hlines)) - - hline = hlines[0] + hline = self.get_alone_element(HistoryLine.objects.exclude(id__in=existing_hline_ids)) self.assertListEqual( [1, hf.name, efilter.name], hline.modifications, ) @@ -573,10 +568,7 @@ def test_xls_export01(self): next(it) # FileRef - filerefs = FileRef.objects.exclude(id__in=existing_fileref_ids) - self.assertEqual(1, len(filerefs)) - - fileref = filerefs[0] + fileref = self.get_alone_element(FileRef.objects.exclude(id__in=existing_fileref_ids)) self.assertTrue(fileref.temporary) self.assertEqual('fakecontact.xls', fileref.basename) self.assertEqual(user, fileref.user) diff --git a/creme/creme_core/tests/views/test_mass_import.py b/creme/creme_core/tests/views/test_mass_import.py index 4b61f05f08..c8ab117240 100644 --- a/creme/creme_core/tests/views/test_mass_import.py +++ b/creme/creme_core/tests/views/test_mass_import.py @@ -151,10 +151,7 @@ def _test_import01(self, builder): ) self.assertNoFormError(response) - jobs = Job.objects.all() - self.assertEqual(1, len(jobs)) - - job = jobs[0] + job = self.get_alone_element(Job.objects.all()) self.assertEqual(self.user, job.user) self.assertIsNone(job.last_run) self.assertIsInstance(job.data, dict) @@ -382,9 +379,7 @@ def _test_import02(self, builder): self.assertFalse(FakePosition.objects.exclude(id__in=sector_ids).exists()) - sectors = FakeSector.objects.exclude(id__in=position_ids) - self.assertEqual(1, len(sectors)) - sector = sectors[0] + sector = self.get_alone_element(FakeSector.objects.exclude(id__in=position_ids)) self.assertEqual(sctr_title, sector.title) created_contacts = {} @@ -458,21 +453,15 @@ def _test_import03(self, builder): job = self._execute_job(response) - contacts = FakeContact.objects.exclude(id__in=contact_ids) - self.assertEqual(1, len(contacts)) - - rei = contacts[0] - relations = Relation.objects.filter(subject_entity=rei, type=employed) - self.assertEqual(1, len(relations)) - - # employer = relations[0].object_entity.get_real_entity() - employer = relations[0].real_object + rei = self.get_alone_element(FakeContact.objects.exclude(id__in=contact_ids)) + employer = self.get_alone_element( + Relation.objects.filter(subject_entity=rei, type=employed) + ).real_object self.assertIsInstance(employer, FakeOrganisation) self.assertEqual(orga_name, employer.name) - results = self._get_job_results(job) - self.assertEqual(1, len(results)) - self.assertFalse(results[0].messages) + result = self.get_alone_element(self._get_job_results(job)) + self.assertFalse(result.messages) def test_not_registered(self): self.login() @@ -652,8 +641,7 @@ def test_relations_with_property_constraint_object01(self): self.assertRelationCount(1, rei, employed.id, seele) self.assertRelationCount(0, rei, employed.id, nerv) - results = self._get_job_results(job) - self.assertEqual(1, len(results)) + result = self.get_alone_element(self._get_job_results(job)) self.assertListEqual( [ Relation.error_messages['missing_subject_property'] % { @@ -662,7 +650,7 @@ def test_relations_with_property_constraint_object01(self): 'property': ptype.text, }, ], - results[0].messages, + result.messages, ) def test_relations_with_property_constraint_object02(self): @@ -741,8 +729,7 @@ def test_relations_with_property_constraint_object02(self): self.assertRelationCount(1, rei, employed.id, seele) self.assertRelationCount(0, rei, employed.id, nerv) - results = self._get_job_results(job) - self.assertEqual(1, len(results)) + result = self.get_alone_element(self._get_job_results(job)) self.assertListEqual( [ Relation.error_messages['refused_subject_property'] % { @@ -751,7 +738,7 @@ def test_relations_with_property_constraint_object02(self): 'property': ptype.text, }, ], - results[0].messages, + result.messages, ) def test_relations_with_property_constraint_subject01(self): @@ -787,8 +774,7 @@ def test_relations_with_property_constraint_subject01(self): rei = self.get_object_or_fail(FakeContact, first_name=first_name, last_name=last_name) self.assertRelationCount(0, rei, employed.id, nerv) - results = self._get_job_results(job) - self.assertEqual(1, len(results)) + result = self.get_alone_element(self._get_job_results(job)) self.assertListEqual( [ Relation.error_messages['missing_subject_property'] % { @@ -797,7 +783,7 @@ def test_relations_with_property_constraint_subject01(self): 'property': ptype.text, }, ], - results[0].messages, + result.messages, ) def test_relations_with_property_constraint_subject02(self): @@ -871,8 +857,7 @@ def test_relations_with_property_constraint_subject03(self): rei = self.get_object_or_fail(FakeContact, first_name=first_name, last_name=last_name) self.assertRelationCount(0, rei, employed.id, nerv) - results = self._get_job_results(job) - self.assertEqual(1, len(results)) + result = self.get_alone_element(self._get_job_results(job)) self.assertListEqual( [ Relation.error_messages['missing_subject_property'] % { @@ -881,7 +866,7 @@ def test_relations_with_property_constraint_subject03(self): 'property': ptype.text, }, ], - results[0].messages, + result.messages, ) def test_relations_with_property_constraint_subject04(self): @@ -949,8 +934,7 @@ def test_relations_with_forbidden_property_constraint_subject01(self): rei = self.get_object_or_fail(FakeContact, first_name=first_name, last_name=last_name) self.assertRelationCount(0, rei, employed.id, nerv) - results = self._get_job_results(job) - self.assertEqual(1, len(results)) + result = self.get_alone_element(self._get_job_results(job)) self.assertListEqual( [ Relation.error_messages['refused_subject_property'] % { @@ -959,7 +943,7 @@ def test_relations_with_forbidden_property_constraint_subject01(self): 'property': ptype.text, }, ], - results[0].messages, + result.messages, ) def test_relations_with_forbidden_property_constraint_subject02(self): @@ -1034,8 +1018,7 @@ def test_relations_with_forbidden_property_constraint_subject03(self): rei = self.get_object_or_fail(FakeContact, first_name=first_name, last_name=last_name) self.assertRelationCount(0, rei, employed.id, nerv) - results = self._get_job_results(job) - self.assertEqual(1, len(results)) + result = self.get_alone_element(self._get_job_results(job)) self.assertListEqual( [ Relation.error_messages['refused_subject_property'] % { @@ -1044,7 +1027,7 @@ def test_relations_with_forbidden_property_constraint_subject03(self): 'property': ptype.text, }, ], - results[0].messages, + result.messages, ) def test_relations_with_forbidden_property_constraint_subject04(self): @@ -1190,10 +1173,7 @@ def get_contact(line_index): results = self._get_job_results(job) self.assertEqual(4, len(results)) - jr_errors = [r for r in results if r.messages] - self.assertEqual(1, len(jr_errors)) - - jr_error = jr_errors[0] + jr_error = self.get_alone_element(r for r in results if r.messages) self.assertEqual([*lines[4]], jr_error.line) self.assertListEqual( [_('Enter a whole number.')], # TODO: add the field verbose name !! @@ -1267,10 +1247,7 @@ def get_contact(line_index): results = self._get_job_results(job) self.assertEqual(2, len(results)) - jr_errors = [r for r in results if r.messages] - self.assertEqual(1, len(jr_errors)) - - jr_error = jr_errors[0] + jr_error = self.get_alone_element(r for r in results if r.messages) self.assertEqual([*lines[2]], jr_error.line) self.assertListEqual( [ @@ -1916,7 +1893,7 @@ def test_import_with_update01(self): ) def test_import_with_update02(self): - "Several existing entities found" + "Several existing entities found." user = self.login() last_name = 'Ayanami' @@ -1950,13 +1927,7 @@ def test_import_with_update02(self): self.assertEqual(count + 1, FakeContact.objects.count()) rei = self.get_object_or_fail(FakeContact, last_name=last_name, first_name=first_name) - results = self._get_job_results(job) - self.assertEqual(1, len(results)) - - jr_errors = [r for r in results if r.messages] - self.assertEqual(1, len(jr_errors)) - - jr_error = jr_errors[0] + jr_error = self.get_alone_element(self._get_job_results(job)) self.assertEqual([last_name, first_name], jr_error.line) self.assertListEqual( [ @@ -2250,10 +2221,7 @@ def test_fields_config_required(self): jresults = MassImportJobResult.objects.filter(job=job) self.assertEqual(2, len(jresults)) - jr_errors = [r for r in jresults if r.messages] - self.assertEqual(1, len(jr_errors)) - - jr_error = jr_errors[0] + jr_error = self.get_alone_element(r for r in jresults if r.messages) self.assertIsNone(jr_error.entity_ctype) self.assertIsNone(jr_error.entity) self.assertListEqual( diff --git a/creme/creme_core/tests/views/test_merge.py b/creme/creme_core/tests/views/test_merge.py index 0140f5fad5..5cf0febf7e 100644 --- a/creme/creme_core/tests/views/test_merge.py +++ b/creme/creme_core/tests/views/test_merge.py @@ -257,20 +257,15 @@ def test_merge01(self): for hline in HistoryLine.objects.filter(id__gt=last_hline_id): new_hlines[hline.type].append(hline) - edition_lines = new_hlines[history.TYPE_EDITION] - self.assertEqual(1, len(edition_lines)) - self.assertEqual(orga01, edition_lines[0].entity.get_real_entity()) + edition_line = self.get_alone_element(new_hlines[history.TYPE_EDITION]) + self.assertEqual(orga01, edition_line.entity.get_real_entity()) # TODO: complete - deletion_lines = new_hlines[history.TYPE_DELETION] - self.assertEqual(1, len(deletion_lines)) - deletion_line = deletion_lines[0] + deletion_line = self.get_alone_element(new_hlines[history.TYPE_DELETION]) self.assertEqual(orga02.entity_type, deletion_line.entity_ctype) self.assertEqual(str(orga02), deletion_line.entity_repr) - prop_lines = new_hlines[history.TYPE_PROP_ADD] - self.assertEqual(1, len(prop_lines)) - prop_line = prop_lines[0] + prop_line = self.get_alone_element(new_hlines[history.TYPE_PROP_ADD]) self.assertEqual(orga01, prop_line.entity.get_real_entity()) self.assertEqual([ptype02.id], prop_line.modifications) @@ -594,21 +589,19 @@ def test_merge_customfields(self): self.assertEqual(contact01.first_name, new_contact01.first_name) self.assertEqual(contact01.last_name, new_contact01.last_name) - cf_01_values = cf_01.value_class.objects.filter( - id__in=(cf_01_value01.id, cf_01_value02.id), + cf_01_value = self.get_alone_element( + cf_01.value_class.objects.filter( + id__in=(cf_01_value01.id, cf_01_value02.id), + ) ) - self.assertEqual(1, len(cf_01_values)) - - cf_01_value = cf_01_values[0] self.assertEqual(contact01.id, cf_01_value.entity_id) self.assertEqual(510, cf_01_value.value) self.assertDoesNotExist(cf_02_value01) - cf_03_values = cf_03.value_class.objects.filter(custom_field=cf_03) - self.assertEqual(1, len(cf_03_values)) - - cf_03_value = cf_03_values[0] + cf_03_value = self.get_alone_element( + cf_03.value_class.objects.filter(custom_field=cf_03) + ) self.assertEqual(contact01.id, cf_03_value.entity_id) self.assertEqual(enum_val1_1, cf_03_value.value) diff --git a/creme/creme_core/tests/views/test_relation.py b/creme/creme_core/tests/views/test_relation.py index 17ecad4963..8ada27039b 100644 --- a/creme/creme_core/tests/views/test_relation.py +++ b/creme/creme_core/tests/views/test_relation.py @@ -1655,10 +1655,7 @@ def test_add_relations_with_same_type_credentials(self): 'entities': [forbidden.id, allowed02.id, self.UNUSED_PK], }, ) - relations = Relation.objects.filter(type=rtype) - self.assertEqual(1, len(relations)) - - relation = relations[0] + relation = self.get_alone_element(Relation.objects.filter(type=rtype)) self.assertEqual(allowed01, relation.subject_entity) self.assertEqual(allowed02, relation.object_entity) diff --git a/creme/crudity/tests/test_inputs.py b/creme/crudity/tests/test_inputs.py index 17e768af03..dd08100d07 100644 --- a/creme/crudity/tests/test_inputs.py +++ b/creme/crudity/tests/test_inputs.py @@ -107,11 +107,10 @@ def test_create_email_input03(self): subject='create_ce', )) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( {'user_id': str(user.id), 'created': '01/02/2003'}, - wactions[0].data + waction.data, ) @skipIfCustomContact @@ -309,8 +308,7 @@ def test_create_email_input08(self): email_input.create(self._get_pop_email( body=body, senders=('creme@crm.org',), subject='create_ce', )) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( { 'user_id': str(user.id), @@ -320,7 +318,7 @@ def test_create_email_input08(self): ' a\ncreme\nentity\n\n ' ), }, - wactions[0].data, + waction.data, ) def test_create_email_input09(self): @@ -369,15 +367,14 @@ def test_create_email_input09(self): email_input.create(self._get_pop_email( body=body, senders=('creme@crm.org',), subject='create_ce', )) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( { 'user_id': str(user.id), 'created': '01/02/2003', 'description': 'I', }, - wactions[0].data, + waction.data, ) def test_create_email_input10(self): @@ -414,15 +411,14 @@ def test_create_email_input10(self): body_html=body_html, senders=('creme@crm.org',), subject='create_ce', )) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( { 'user_id': user.id, 'created': '01-02-2003', 'description': 'I\n want to\n create a \ncreme entity\n', }, - wactions[0].data, + waction.data, ) def test_create_email_input11(self): @@ -464,15 +460,14 @@ def test_create_email_input11(self): body_html=body_html, senders=('creme@crm.org',), subject='create_ce', )) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( { 'user_id': user.id, 'created': '01-02-2003', 'description': 'I\n want to\n create a \ncreme entity\n', }, - wactions[0].data, + waction.data, ) def test_create_email_input12(self): @@ -507,20 +502,19 @@ def test_create_email_input12(self): """ - self.assertEqual(0, WaitingAction.objects.count()) + self.assertFalse(WaitingAction.objects.count()) email_input.create(self._get_pop_email( body_html=body_html, senders=('creme@crm.org',), subject='create_ce', )) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( { 'user_id': user.id, 'created': '01-02-2003', 'description': 'I', }, - wactions[0].data, + waction.data, ) def test_create_email_input13(self): @@ -545,10 +539,11 @@ def test_create_email_input13(self): )) self.assertFalse(WaitingAction.objects.filter(user=None)) - wactions = WaitingAction.objects.filter(user=get_user_model().objects.get_admin()) - self.assertEqual(1, len(wactions)) + waction = self.get_alone_element( + WaitingAction.objects.filter(user=get_user_model().objects.get_admin()) + ) self.assertDictEqual( - {'user_id': str(user.id), 'created': '01/02/2003'}, wactions[0].data, + {'user_id': str(user.id), 'created': '01/02/2003'}, waction.data, ) @skipIfCustomContact @@ -750,10 +745,7 @@ def test_create_contact01(self): subject='create_contact', )) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) - - wa = wactions[0] + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( { 'user_id': str(user.id), @@ -765,10 +757,12 @@ def test_create_contact01(self): 'birthday': '02/08/1987', 'description': 'A plumber', }, - wa.data, + waction.data, ) - email_input.get_backend(CrudityBackend.normalize_subject('create_contact')).create(wa) + email_input.get_backend( + CrudityBackend.normalize_subject('create_contact') + ).create(waction) contact = self.get_object_or_fail(Contact, first_name='Mario', last_name='Bros') self.assertEqual(user, contact.user) @@ -824,12 +818,11 @@ class ActivityFakeBackend(CrudityBackend): subject=subject, )) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) + waction = self.get_alone_element(WaitingAction.objects.all()) is_created, activity = email_input.get_backend( CrudityBackend.normalize_subject(subject) - ).create(wactions[0]) + ).create(waction) self.assertTrue(is_created) self.assertIsInstance(activity, Activity) @@ -985,10 +978,7 @@ def test_sandbox01(self): self.assertIsInstance(ok, CrudityBackend) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) - - waction = wactions[0] + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( { 'user_id': '1', @@ -996,7 +986,7 @@ def test_sandbox01(self): 'last_name': 'Baggins', 'description': 'this hobbit will\nsave the world', }, - waction.data + waction.data, ) owner = waction.user @@ -1029,8 +1019,7 @@ def test_sandbox02(self): self.assertIsNotNone(ok) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( { 'user_id': '1', @@ -1038,7 +1027,7 @@ def test_sandbox02(self): 'last_name': 'Baggins', # 'description': 'this hobbit will\nsave the world', }, - wactions[0].data + waction.data, ) def test_sandbox_by_user01(self): @@ -1063,17 +1052,14 @@ def test_sandbox_by_user01(self): self.assertIsNotNone(ok) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) - - waction = wactions[0] + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( { 'user_id': '1', 'first_name': 'Bilbo', 'last_name': 'Baggins', }, - waction.data + waction.data, ) self.assertEqual(self.other_user, waction.user) @@ -1109,18 +1095,16 @@ def test_sandbox_by_user02(self): ], ) - wactions = WaitingAction.objects.all() - self.assertEqual(1, len(wactions)) - - waction = wactions[0] + waction = self.get_alone_element(WaitingAction.objects.all()) self.assertDictEqual( { 'user_id': '1', 'first_name': 'Samwise', 'last_name': 'Gamgee', }, - waction.data + waction.data, ) + owner = waction.user self.assertIsNotNone(owner) self.assertNotEqual(self.other_user, owner) diff --git a/creme/crudity/tests/test_views.py b/creme/crudity/tests/test_views.py index 4e594fbb48..13fbaf43b0 100644 --- a/creme/crudity/tests/test_views.py +++ b/creme/crudity/tests/test_views.py @@ -566,10 +566,7 @@ def test_actions_fetch01(self): ldata = response.json() self.assertEqual([], ldata) - pop_instances = FakePOP3.instances - self.assertEqual(1, len(pop_instances)) - - pop_instance = pop_instances[0] + pop_instance = self.get_alone_element(FakePOP3.instances) self.assertIsInstance(pop_instance, FakePOP3_SSL) # Because CREME_GET_EMAIL_SSL=True self.assertEqual('pop.test.org', pop_instance._host) self.assertEqual(123, pop_instance._port) @@ -623,8 +620,7 @@ def test_job01(self): self.assertGET200(job.get_absolute_url()) - jresults = JobResult.objects.filter(job=job) - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -633,7 +629,7 @@ def test_job01(self): 1 ).format(count=1), ], - jresults[0].messages + jresult.messages, ) self.assertListEqual([], queue.started_jobs) @@ -692,8 +688,7 @@ def test_job02(self): # ----------------------------- crudity_synchronize_type.execute(job) - jresults = JobResult.objects.filter(job=job) - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -702,7 +697,7 @@ def test_job02(self): 1 ).format(count=1), ], - jresults[0].messages + jresult.messages, ) calls_args = self.FakeContactBackend.calls_args diff --git a/creme/cti/tests.py b/creme/cti/tests.py index 6e96297f13..71a09a63ec 100644 --- a/creme/cti/tests.py +++ b/creme/cti/tests.py @@ -95,10 +95,7 @@ def test_add_phonecall01(self): contact = Contact.objects.create(user=user, first_name='Bean', last_name='Bandit') self.assertPOST200(self.ADD_PCALL_URL, data={'entity_id': contact.id}) - pcalls = Activity.objects.filter(type=atype) - self.assertEqual(1, len(pcalls)) - - pcall = pcalls[0] + pcall = self.get_alone_element(Activity.objects.filter(type=atype)) self.assertEqual(user, pcall.user) self.assertIn(str(contact), pcall.title) self.assertTrue(pcall.description) @@ -129,10 +126,9 @@ def test_add_phonecall03(self): orga = Organisation.objects.create(user=user, name='Gunsmith Cats') self.assertPOST200(self.ADD_PCALL_URL, data={'entity_id': orga.id}) - pcalls = Activity.objects.filter(type=a_constants.ACTIVITYTYPE_PHONECALL) - self.assertEqual(1, len(pcalls)) - - pcall = pcalls[0] + pcall = self.get_alone_element( + Activity.objects.filter(type=a_constants.ACTIVITYTYPE_PHONECALL) + ) self.assertRelationCount(0, orga, a_constants.REL_SUB_PART_2_ACTIVITY, pcall) self.assertRelationCount(1, orga, a_constants.REL_SUB_LINKED_2_ACTIVITY, pcall) @@ -302,10 +298,9 @@ def test_create_phonecall01(self): contact = Contact.objects.create(user=user, first_name='Bean', last_name='Bandit') self.assertPOST(302, self._build_add_pcall_url(contact)) - pcalls = Activity.objects.filter(type=a_constants.ACTIVITYTYPE_PHONECALL) - self.assertEqual(1, len(pcalls)) - - pcall = pcalls[0] + pcall = self.get_alone_element( + Activity.objects.filter(type=a_constants.ACTIVITYTYPE_PHONECALL) + ) self.assertEqual(user, pcall.user) self.assertIn(str(contact), pcall.title) self.assertTrue(pcall.description) @@ -326,10 +321,7 @@ def test_create_phonecall02(self): self.assertPOST(302, self._build_add_pcall_url(self.contact)) - activities = Activity.objects.all() - self.assertEqual(1, len(activities)) - - phone_call = activities[0] + phone_call = self.get_alone_element(Activity.objects.all()) self.assertRelationCount(1, self.contact, a_constants.REL_SUB_PART_2_ACTIVITY, phone_call) calendar = Calendar.objects.get_default_calendar(user) diff --git a/creme/documents/tests/test_document.py b/creme/documents/tests/test_document.py index 4ad1f9cf8d..3050d8cfa4 100644 --- a/creme/documents/tests/test_document.py +++ b/creme/documents/tests/test_document.py @@ -124,10 +124,7 @@ def test_createview01(self): ) self.assertNoFormError(response) - docs = Document.objects.all() - self.assertEqual(1, len(docs)) - - doc = docs[0] + doc = self.get_alone_element(Document.objects.all()) self.assertEqual(title, doc.title) self.assertEqual(description, doc.description) self.assertEqual(folder, doc.linked_folder) @@ -648,15 +645,12 @@ def test_listview_actions(self): user = self.login() doc1 = self._create_doc('Test doc #1') - dl_actions = [ + download_action = self.get_alone_element( action for action in actions.actions_registry .instance_actions(user=user, instance=doc1) if isinstance(action, DownloadAction) - ] - self.assertEqual(1, len(dl_actions)) - - download_action = dl_actions[0] + ) self.assertEqual('redirect', download_action.type) self.assertEqual( doc1.get_download_absolute_url(), @@ -810,10 +804,10 @@ def test_create(self): ) self.assertGET200(url) + # --- content = 'Yes I am the content (DocumentQuickFormTestCase.test_create)' file_obj = self.build_filedata(content) folder = Folder.objects.all()[0] - self.assertNoFormError(self.client.post( url, follow=True, data={ @@ -823,10 +817,7 @@ def test_create(self): }, )) - docs = Document.objects.all() - self.assertEqual(1, len(docs)) - - doc = docs[0] + doc = self.get_alone_element(Document.objects.all()) self.assertEqual(Path('documents/' + file_obj.base_name), Path(doc.filedata.name)) self.assertEqual('', doc.description) self.assertEqual(folder, doc.linked_folder) @@ -864,10 +855,7 @@ def test_add_csv_doc01(self): ) self.assertNoFormError(response) - docs = Document.objects.all() - self.assertEqual(1, len(docs)) - - doc = docs[0] + doc = self.get_alone_element(Document.objects.all()) folder = get_csv_folder_or_create(user) self.assertEqual(Path('documents/' + file_obj.base_name), Path(doc.filedata.name)) self.assertEqual('', doc.description) @@ -927,10 +915,7 @@ def test_add_image_doc01(self): ) self.assertNoFormError(response) - docs = Document.objects.all() - self.assertEqual(1, len(docs)) - - doc = docs[0] + doc = self.get_alone_element(Document.objects.all()) title = doc.title self.assertStartsWith(title, 'creme_22') self.assertEndsWith(title, '.png') diff --git a/creme/documents/tests/test_folder.py b/creme/documents/tests/test_folder.py index c8eef4c4f1..5c17a8b132 100644 --- a/creme/documents/tests/test_folder.py +++ b/creme/documents/tests/test_folder.py @@ -654,15 +654,12 @@ def test_listview_actions(self): user = self.login() folder = Folder.objects.create(user=user, title='My folder') - explore_actions = [ + explore_action = self.get_alone_element( action for action in actions.actions_registry .instance_actions(user=user, instance=folder) if isinstance(action, ExploreFolderAction) - ] - self.assertEqual(1, len(explore_actions)) - - explore_action = explore_actions[0] + ) self.assertEqual('redirect', explore_action.type) self.assertEqual( f'{folder.get_lv_absolute_url()}?parent_id={folder.id}', @@ -671,7 +668,8 @@ def test_listview_actions(self): self.assertTrue(explore_action.is_enabled) self.assertTrue(explore_action.is_visible) self.assertEqual( - _('List sub-folders of «{}»').format(folder), explore_action.help_text + _('List sub-folders of «{}»').format(folder), + explore_action.help_text, ) def test_folder_clone01(self): diff --git a/creme/emails/tests/synchronization/test_job.py b/creme/emails/tests/synchronization/test_job.py index a84d8121a0..9c01396cfc 100644 --- a/creme/emails/tests/synchronization/test_job.py +++ b/creme/emails/tests/synchronization/test_job.py @@ -98,15 +98,14 @@ def test_job01(self): self.assertFalse(EmailToSync.objects.all()) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ _('There was no message on "{host}" for the user "{user}"').format( host=item.host, user=item.username, ) ], - jresults[0].messages, + jresult.messages, ) def test_job02(self): @@ -152,10 +151,7 @@ def test_job02(self): pop_instance.retr.assert_called_once_with(msg_id) pop_instance.dele.assert_called_once_with(msg_id) - emails_to_sync = [*EmailToSync.objects.all()] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.all()) self.assertEqual(user, e2sync.user) self.assertEqual(subject, e2sync.subject) self.assertEqual(body + '\n', e2sync.body) @@ -173,8 +169,7 @@ def test_job02(self): ], ) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -185,7 +180,7 @@ def test_job02(self): count=1, host=item.host, user=item.username, ) ], - jresults[0].messages, + jresult.messages, ) def test_job03(self): @@ -286,8 +281,7 @@ def test_job03(self): self.assertHTMLEqual(body_html2, e2sync2.body_html) self.assertIsNone(e2sync2.date) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -298,7 +292,7 @@ def test_job03(self): count=2, host=item.host, user=item.username, ), ], - jresults[0].messages, + jresult.messages, ) def test_job_assign_user01(self): @@ -425,15 +419,11 @@ def test_job_assign_user02(self): self.assertEqual(2, pop_instance.retr.call_count) self.assertEqual(2, pop_instance.dele.call_count) - emails_to_sync = [*EmailToSync.objects.all()] - self.assertEqual(1, len(emails_to_sync)) - - e2sync1 = emails_to_sync[0] + e2sync1 = self.get_alone_element(EmailToSync.objects.all()) self.assertEqual(subject, e2sync1.subject) self.assertEqual(user, e2sync1.user) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -449,7 +439,7 @@ def test_job_assign_user02(self): 1 ).format(count=1), ], - jresults[0].messages, + jresult.messages, ) def test_job_invalid_data01(self): @@ -484,8 +474,7 @@ def test_job_invalid_data01(self): self.assertFalse(EmailToSync.objects.all()) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -501,7 +490,7 @@ def test_job_invalid_data01(self): 1 ).format(count=1), ], - jresults[0].messages, + jresult.messages, ) def test_job_invalid_data02(self): @@ -529,8 +518,7 @@ def test_job_invalid_data02(self): self.assertFalse(EmailToSync.objects.all()) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -546,7 +534,7 @@ def test_job_invalid_data02(self): 1 ).format(count=1), ], - jresults[0].messages, + jresult.messages, ) @skipIfCustomContact @@ -596,10 +584,7 @@ def test_job_related_persons01(self): # Go ! entity_emails_sync_type.execute(job) - emails_to_sync = [*EmailToSync.objects.order_by('id')] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.order_by('id')) self.assertEqual(user, e2sync.user) self.assertListEqual( @@ -667,10 +652,7 @@ def test_job_related_persons02(self): # Go ! entity_emails_sync_type.execute(job) - emails_to_sync = [*EmailToSync.objects.order_by('id')] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.order_by('id')) self.assertEqual(user, e2sync.user) self.assertListEqual( @@ -738,10 +720,7 @@ def test_job_related_persons_credentials01(self, cred): # Go ! entity_emails_sync_type.execute(job) - emails_to_sync = [*EmailToSync.objects.order_by('id')] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.order_by('id')) self.assertEqual(user, e2sync.user) self.assertListEqual( @@ -847,10 +826,7 @@ def test_job_forwarded_email(self): # Go ! entity_emails_sync_type.execute(job) - emails_to_sync = [*EmailToSync.objects.order_by('id')] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.order_by('id')) self.assertEqual(user, e2sync.user) filter_person = e2sync.related_persons.filter @@ -906,10 +882,7 @@ def test_job_attachment01(self): # Go ! entity_emails_sync_type.execute(job) - emails_to_sync = [*EmailToSync.objects.all()] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.all()) self.assertEqual(subject, e2sync.subject) self.assertEqual(body, e2sync.body) self.assertEqual('', e2sync.body_html) @@ -970,10 +943,7 @@ def test_job_attachment02(self): # Go ! entity_emails_sync_type.execute(job) - emails_to_sync = [*EmailToSync.objects.all()] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.all()) self.assertEqual(subject, e2sync.subject) self.assertFalse(e2sync.attachments.all()) @@ -991,16 +961,15 @@ def test_job_error01(self): self.assertFalse(EmailToSync.objects.all()) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ _( 'Error while retrieving emails on "{host}" for the user "{user}" ' '[original error: {error}]' - ).format(host=item.host, user=item.username, error=error_msg) + ).format(host=item.host, user=item.username, error=error_msg), ], - jresults[0].messages, + jresult.messages, ) def test_job_error02(self): @@ -1030,8 +999,7 @@ def test_job_error02(self): self.assertFalse(EmailToSync.objects.all()) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( # TODO? # [ @@ -1045,7 +1013,7 @@ def test_job_error02(self): host=item.host, user=item.username, ) ], - jresults[0].messages, + jresult.messages, ) def test_job_error03(self): @@ -1091,15 +1059,11 @@ def test_job_error03(self): pop_instance.dele.assert_called_once_with(msg_id2) pop_instance.quit.assert_called_once() - emails_to_sync = [*EmailToSync.objects.all()] - self.assertEqual(1, len(emails_to_sync)) - - e2sync1 = emails_to_sync[0] + e2sync1 = self.get_alone_element(EmailToSync.objects.all()) self.assertEqual(subject, e2sync1.subject) self.assertEqual('', e2sync1.body) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -1113,7 +1077,7 @@ def test_job_error03(self): 2 ).format(count=2), ], - jresults[0].messages, + jresult.messages, ) @@ -1183,15 +1147,14 @@ def test_job01(self): self.assertFalse(EmailToSync.objects.all()) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ _('There was no message on "{host}" for the user "{user}"').format( host=item.host, user=item.username, ) ], - jresults[0].messages, + jresult.messages, ) def test_job02(self): @@ -1235,10 +1198,7 @@ def test_job02(self): imap_instance.store.assert_called_once_with(msg_id, '+FLAGS', r'\Deleted') imap_instance.expunge.assert_called_once() - emails_to_sync = [*EmailToSync.objects.all()] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.all()) self.assertEqual(user, e2sync.user) self.assertEqual(subject, e2sync.subject) self.assertEqual(body + '\n', e2sync.body) @@ -1256,8 +1216,7 @@ def test_job02(self): ], ) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -1268,7 +1227,7 @@ def test_job02(self): count=1, host=item.host, user=item.username, ) ], - jresults[0].messages, + jresult.messages, ) def test_job03(self): @@ -1370,8 +1329,7 @@ def test_job03(self): self.assertHTMLEqual(body_html2, e2sync2.body_html) self.assertIsNone(e2sync2.date) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -1382,7 +1340,7 @@ def test_job03(self): count=2, host=item.host, user=item.username, ), ], - jresults[0].messages, + jresult.messages, ) def test_job_assign_user01(self): @@ -1511,15 +1469,11 @@ def test_job_assign_user02(self): self.assertEqual(2, imap_instance.fetch.call_count) self.assertEqual(2, imap_instance.store.call_count) - emails_to_sync = [*EmailToSync.objects.all()] - self.assertEqual(1, len(emails_to_sync)) - - e2sync1 = emails_to_sync[0] + e2sync1 = self.get_alone_element(EmailToSync.objects.all()) self.assertEqual(subject, e2sync1.subject) self.assertEqual(user, e2sync1.user) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -1535,7 +1489,7 @@ def test_job_assign_user02(self): 1 ).format(count=1), ], - jresults[0].messages, + jresult.messages, ) def test_job_invalid_data01(self): @@ -1571,8 +1525,7 @@ def test_job_invalid_data01(self): self.assertFalse(EmailToSync.objects.all()) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -1588,7 +1541,7 @@ def test_job_invalid_data01(self): 1 ).format(count=1), ], - jresults[0].messages, + jresult.messages, ) def test_job_invalid_data02(self): @@ -1616,8 +1569,7 @@ def test_job_invalid_data02(self): self.assertFalse(EmailToSync.objects.all()) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -1633,7 +1585,7 @@ def test_job_invalid_data02(self): 1 ).format(count=1), ], - jresults[0].messages, + jresult.messages, ) @skipIfCustomContact @@ -1683,10 +1635,7 @@ def test_job_related_persons01(self): # Go ! entity_emails_sync_type.execute(job) - emails_to_sync = [*EmailToSync.objects.order_by('id')] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.order_by('id')) self.assertEqual(user, e2sync.user) self.assertListEqual( @@ -1754,10 +1703,7 @@ def test_job_related_persons02(self): # Go ! entity_emails_sync_type.execute(job) - emails_to_sync = [*EmailToSync.objects.order_by('id')] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.order_by('id')) self.assertEqual(user, e2sync.user) self.assertListEqual( @@ -1824,10 +1770,7 @@ def test_job_attachment01(self): # Go ! entity_emails_sync_type.execute(job) - emails_to_sync = [*EmailToSync.objects.all()] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.all()) self.assertEqual(subject, e2sync.subject) self.assertEqual(body, e2sync.body) self.assertEqual('', e2sync.body_html) @@ -1889,10 +1832,7 @@ def test_job_attachment02(self): # Go ! entity_emails_sync_type.execute(job) - emails_to_sync = [*EmailToSync.objects.all()] - self.assertEqual(1, len(emails_to_sync)) - - e2sync = emails_to_sync[0] + e2sync = self.get_alone_element(EmailToSync.objects.all()) self.assertEqual(subject, e2sync.subject) self.assertFalse(e2sync.attachments.all()) @@ -1908,8 +1848,7 @@ def test_job_error01(self): self.assertFalse(EmailToSync.objects.all()) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ _( @@ -1917,7 +1856,7 @@ def test_job_error01(self): '[original error: {error}]' ).format(host=item.host, user=item.username, error=error_msg), ], - jresults[0].messages, + jresult.messages, ) def test_job_error02(self): @@ -1947,8 +1886,7 @@ def test_job_error02(self): self.assertFalse(EmailToSync.objects.all()) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( # TODO? # [ @@ -1962,7 +1900,7 @@ def test_job_error02(self): host=item.host, user=item.username, ) ], - jresults[0].messages, + jresult.messages, ) def test_job_error03(self): @@ -2012,15 +1950,11 @@ def test_job_error03(self): imap_instance.store.assert_called_once_with(msg_id2, '+FLAGS', r'\Deleted') imap_instance.logout.assert_called_once() - emails_to_sync = [*EmailToSync.objects.all()] - self.assertEqual(1, len(emails_to_sync)) - - e2sync1 = emails_to_sync[0] + e2sync1 = self.get_alone_element(EmailToSync.objects.all()) self.assertEqual(subject, e2sync1.subject) self.assertEqual('', e2sync1.body) - jresults = [*JobResult.objects.filter(job=job)] - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(JobResult.objects.filter(job=job)) self.assertListEqual( [ ngettext( @@ -2034,5 +1968,5 @@ def test_job_error03(self): 1 ).format(count=1), ], - jresults[0].messages, + jresult.messages, ) diff --git a/creme/emails/tests/synchronization/test_views.py b/creme/emails/tests/synchronization/test_views.py index dc5792df5a..868589d8b6 100644 --- a/creme/emails/tests/synchronization/test_views.py +++ b/creme/emails/tests/synchronization/test_views.py @@ -1027,10 +1027,7 @@ def test_accept_email_to_sync01(self): self.assertRelationCount(0, email1, REL_SUB_MAIL_SENT, contact1) self.assertRelationCount(1, email1, REL_SUB_MAIL_RECEIVED, contact2) - attachments = [*email1.attachments.all()] - self.assertEqual(1, len(attachments)) - - attachment = attachments[0] + attachment = self.get_alone_element(email1.attachments.all()) self.assertEqual(file_name, attachment.title) path = attachment.filedata.path @@ -1144,9 +1141,8 @@ def test_accept_email_to_sync02(self): self.assertPOST200(self.ACCEPT_EMAIL_URL, data={'ids': e2s.id}) email = self.get_object_or_fail(EntityEmail, subject=e2s.subject) - attachments = [*email.attachments.all()] - self.assertEqual(1, len(attachments)) - self.assertEqual(folder, attachments[0].linked_folder) + attachment = self.get_alone_element(email.attachments.all()) + self.assertEqual(folder, attachment.linked_folder) def test_accept_email_to_sync_perm01(self): "No emails credentials." diff --git a/creme/emails/tests/test_mail.py b/creme/emails/tests/test_mail.py index b76b0dea7f..3d412f0328 100644 --- a/creme/emails/tests/test_mail.py +++ b/creme/emails/tests/test_mail.py @@ -186,10 +186,7 @@ def test_createview01(self): ) # --- - messages = mail.outbox - self.assertEqual(1, len(messages)) - - message = messages[0] + message = self.get_alone_element(mail.outbox) self.assertEqual(subject, message.subject) self.assertEqual(body, message.body) self.assertEqual([recipient], message.recipients()) @@ -1173,15 +1170,12 @@ def test_listview_instance_actions(self): user = self.login() email = self._create_email() - resend_actions = [ + resend_action = self.get_alone_element( action for action in actions.actions_registry .instance_actions(user=user, instance=email) if isinstance(action, EntityEmailResendAction) - ] - self.assertEqual(1, len(resend_actions)) - - resend_action = resend_actions[0] + ) self.assertEqual('email-resend', resend_action.type) self.assertEqual(reverse('emails__resend_emails'), resend_action.url) self.assertDictEqual( @@ -1196,15 +1190,12 @@ def test_listview_instance_actions(self): def test_listview_bulk_actions(self): user = self.login() - resend_actions = [ + resend_action = self.get_alone_element( action for action in actions.actions_registry .bulk_actions(user=user, model=EntityEmail) if isinstance(action, BulkEntityEmailResendAction) - ] - self.assertEqual(1, len(resend_actions)) - - resend_action = resend_actions[0] + ) self.assertEqual('email-resend-selection', resend_action.type) self.assertEqual(reverse('emails__resend_emails'), resend_action.url) self.assertIsNone(resend_action.action_data) @@ -1293,10 +1284,7 @@ def test_job01(self): self._send_mails(job) - messages = mail.outbox - self.assertEqual(1, len(messages)) - - message = messages[0] + message = self.get_alone_element(mail.outbox) self.assertEqual(email.subject, message.subject) self.assertEqual(email.body, message.body) @@ -1317,10 +1305,7 @@ def test_job02(self): self._send_mails(job) - messages = mail.outbox - self.assertEqual(1, len(messages)) - - message = messages[0] + message = self.get_alone_element(mail.outbox) self.assertEqual(email.subject, message.subject) self.assertEqual(email.body, message.body) diff --git a/creme/emails/tests/test_sending.py b/creme/emails/tests/test_sending.py index 8648e7860c..2c291d5860 100644 --- a/creme/emails/tests/test_sending.py +++ b/creme/emails/tests/test_sending.py @@ -286,10 +286,9 @@ def test_create01(self): }, )) - sendings = self.refresh(camp).sendings_set.all() # refresh is probably be useless... - self.assertEqual(1, len(sendings)) - - sending = sendings[0] + sending = self.get_alone_element( + self.refresh(camp).sendings_set.all() # refresh is probably be useless... + ) self.assertEqual(EmailSending.Type.IMMEDIATE, sending.type) self.assertEqual(EmailSending.State.PLANNED, sending.state) self.assertEqual(subject, sending.subject) diff --git a/creme/emails/tests/test_utils.py b/creme/emails/tests/test_utils.py index e90b58616e..9284f0449d 100644 --- a/creme/emails/tests/test_utils.py +++ b/creme/emails/tests/test_utils.py @@ -147,10 +147,7 @@ def test_sender02(self): self.assertEqual(f'{body}\n--\n{signature.body}', message.body) self.assertEqual(mail.sender, message.from_email) - alternatives = message.alternatives - self.assertEqual(1, len(alternatives)) - - alternative = alternatives[0] + alternative = self.get_alone_element(message.alternatives) self.assertEqual('text/html', alternative[1]) self.maxDiff = None # self.assertEqual( diff --git a/creme/geolocation/tests/test_populate.py b/creme/geolocation/tests/test_populate.py index 3af0a42dd7..0836f6954f 100644 --- a/creme/geolocation/tests/test_populate.py +++ b/creme/geolocation/tests/test_populate.py @@ -425,11 +425,10 @@ def test_create_geoaddress_no_town(self): self.command.populate_addresses() - geo_addresses = GeoAddress.objects.all() - self.assertEqual(1, len(geo_addresses)) + geo_address = self.get_alone_element(GeoAddress.objects.all()) address = self.refresh(address) - self.assertEqual(address.geoaddress, geo_addresses[0]) + self.assertEqual(address.geoaddress, geo_address) self.assertGeoAddress( address.geoaddress, address=address, @@ -466,11 +465,10 @@ def test_create_geoaddress_with_town(self): self.command.populate_addresses() - geo_addresses = GeoAddress.objects.all() - self.assertEqual(1, len(geo_addresses)) + geo_address = self.get_alone_element(GeoAddress.objects.all()) address = self.refresh(address) - self.assertEqual(address.geoaddress, geo_addresses[0]) + self.assertEqual(address.geoaddress, geo_address) self.assertGeoAddress( address.geoaddress, address=address, diff --git a/creme/geolocation/tests/test_views.py b/creme/geolocation/tests/test_views.py index 82bc1442bb..f806d9fa97 100644 --- a/creme/geolocation/tests/test_views.py +++ b/creme/geolocation/tests/test_views.py @@ -41,10 +41,7 @@ def test_set_address_info(self): self.assertGET405(url, data={**data1, 'id': address.id}) self.assertPOST200(url, data={**data1, 'id': address.id}) - geoaddresses = GeoAddress.objects.all() - self.assertEqual(1, len(geoaddresses)) - - geoaddress = geoaddresses[0] + geoaddress = self.get_alone_element(GeoAddress.objects.all()) self.assertGeoAddress(geoaddress, address=address, draggable=True, **data1) self.assertEqual(self.refresh(address).geoaddress, geoaddress) @@ -56,9 +53,8 @@ def test_set_address_info(self): } self.assertPOST200(url, data={**data2, 'id': address.id}) - geoaddresses = GeoAddress.objects.all() - self.assertEqual(1, len(geoaddresses)) - self.assertGeoAddress(geoaddresses[0], address=address, draggable=True, **data2) + geoaddress = self.get_alone_element(GeoAddress.objects.all()) + self.assertGeoAddress(geoaddress, address=address, draggable=True, **data2) @skipIfCustomOrganisation @skipIfCustomAddress @@ -95,10 +91,9 @@ def test_set_address_info_without_geoaddress(self): } self.assertPOST200(url, data={**data2, 'id': address.id}) - geoaddresses = GeoAddress.objects.all() - self.assertEqual(1, len(geoaddresses)) + geoaddress = self.get_alone_element(GeoAddress.objects.all()) self.assertGeoAddress( - geoaddresses[0], address=address, draggable=True, **data2 + geoaddress, address=address, draggable=True, **data2 ) def test_set_address_info_missing_address(self): @@ -132,10 +127,7 @@ def test_set_address_info_missing_argument(self): } self.assertPOST200(self.SET_ADDRESS_URL, data={**data, 'id': address.id}) - geoaddresses = GeoAddress.objects.all() - self.assertEqual(1, len(geoaddresses)) - - geoaddress = geoaddresses[0] + geoaddress = self.get_alone_element(GeoAddress.objects.all()) self.assertGeoAddress(geoaddress, address=address, draggable=True, **data) self.assertEqual(self.refresh(address).geoaddress, geoaddress) @@ -148,9 +140,8 @@ def test_set_address_info_missing_argument(self): }, ) - geoaddresses = GeoAddress.objects.all() - self.assertEqual(1, len(geoaddresses)) - self.assertGeoAddress(geoaddresses[0], address=address, draggable=True, **data) + geoaddress = self.get_alone_element(GeoAddress.objects.all()) + self.assertGeoAddress(geoaddress[0], address=address, draggable=True, **data) @skipIfCustomOrganisation @skipIfCustomAddress @@ -158,7 +149,7 @@ def test_set_address_info_credentials(self): self.login(is_superuser=False, allowed_apps=('creme_core', 'geolocation', 'persons')) SetCredentials.objects.create( - role=self.user.role, + role=self.role, ctype=Organisation, value=EntityCredentials._ALL_CREDS, set_type=SetCredentials.ESET_OWN, diff --git a/creme/opportunities/tests/test_billing.py b/creme/opportunities/tests/test_billing.py index 3df15d463f..8d249f68a6 100644 --- a/creme/opportunities/tests/test_billing.py +++ b/creme/opportunities/tests/test_billing.py @@ -141,10 +141,7 @@ def test_generate_new_doc01(self): self.assertGET405(url) self.assertPOST200(url, follow=True) - quotes = Quote.objects.all() - self.assertEqual(1, len(quotes)) - - quote = quotes[0] + quote = self.get_alone_element(Quote.objects.all()) self.assertDatetimesAlmostEqual(date.today(), quote.issuing_date) self.assertEqual(1, quote.status_id) self.assertTrue(quote.number) @@ -184,9 +181,7 @@ def test_generate_new_doc02(self): quote1 = Quote.objects.all()[0] self.client.post(url) - quotes = Quote.objects.exclude(pk=quote1.id) - self.assertEqual(1, len(quotes)) - quote2 = quotes[0] + quote2 = self.get_alone_element(Quote.objects.exclude(pk=quote1.id)) self.assertRelationCount(1, quote2, REL_SUB_BILL_ISSUED, emitter) self.assertRelationCount(1, quote2, REL_SUB_BILL_RECEIVED, target) @@ -211,13 +206,11 @@ def test_generate_new_doc03(self): invoice1 = Invoice.objects.all()[0] self.client.post(url) - invoices = Invoice.objects.exclude(pk=invoice1.id) - self.assertEqual(1, len(invoices)) + invoice2 = self.get_alone_element(Invoice.objects.exclude(pk=invoice1.id)) - invoices2 = invoices[0] - self.assertRelationCount(1, invoices2, REL_SUB_BILL_ISSUED, emitter) - self.assertRelationCount(1, invoices2, REL_SUB_BILL_RECEIVED, target) - self.assertRelationCount(1, invoices2, constants.REL_SUB_LINKED_INVOICE, opportunity) + self.assertRelationCount(1, invoice2, REL_SUB_BILL_ISSUED, emitter) + self.assertRelationCount(1, invoice2, REL_SUB_BILL_RECEIVED, target) + self.assertRelationCount(1, invoice2, constants.REL_SUB_LINKED_INVOICE, opportunity) self.assertRelationCount(1, invoice1, REL_SUB_BILL_ISSUED, emitter) self.assertRelationCount(1, invoice1, REL_SUB_BILL_RECEIVED, target) diff --git a/creme/opportunities/tests/test_mass_import.py b/creme/opportunities/tests/test_mass_import.py index f1833c9328..1002745657 100644 --- a/creme/opportunities/tests/test_mass_import.py +++ b/creme/opportunities/tests/test_mass_import.py @@ -222,10 +222,7 @@ def test_mass_import02(self): self.assertEqual(count, Opportunity.objects.count()) self.assertFalse(SalesPhase.objects.filter(name=sp1_name).count()) - results = self._get_job_results(job) - self.assertEqual(1, len(results)) - - result = results[0] + result = self.get_alone_element(self._get_job_results(job)) self.assertIsNone(result.entity) # 2 errors: retrieving of SalesPhase failed, creation of Opportunity failed self.assertEqual(2, len(result.messages)) diff --git a/creme/persons/tests/contact/test_main.py b/creme/persons/tests/contact/test_main.py index 1aeec708e5..9aef89c807 100644 --- a/creme/persons/tests/contact/test_main.py +++ b/creme/persons/tests/contact/test_main.py @@ -1523,10 +1523,9 @@ def test_command_create_staffuser(self): Command as StaffCommand, ) - super_users = CremeUser.objects.filter(is_superuser=True, is_staff=False) - self.assertEqual(1, len(super_users)) - - super_user1 = super_users[0] + super_user1 = self.get_alone_element( + CremeUser.objects.filter(is_superuser=True, is_staff=False) + ) # This superuser should not be used username2 = 'kirika' diff --git a/creme/persons/tests/contact/test_mass_import.py b/creme/persons/tests/contact/test_mass_import.py index 361d6525b5..98ae6ba5ad 100644 --- a/creme/persons/tests/contact/test_mass_import.py +++ b/creme/persons/tests/contact/test_mass_import.py @@ -316,11 +316,10 @@ def test_address_fields_config_update(self): self.assertFalse(addr1.city) self.assertFalse(addr1.address) # Not address_val1 - jresults = self._get_job_results(job) - self.assertEqual(1, len(jresults)) + jresult = self.get_alone_element(self._get_job_results(job)) self.assertListEqual( [ _('The field «{}» has been configured as required.').format(_('City')), ], - jresults[0].messages, + jresult.messages, ) diff --git a/creme/persons/tests/organisation/test_main.py b/creme/persons/tests/organisation/test_main.py index e58acd81d1..3d76f6f5b6 100644 --- a/creme/persons/tests/organisation/test_main.py +++ b/creme/persons/tests/organisation/test_main.py @@ -833,10 +833,7 @@ def test_delete02(self): "Cannot delete the last managed organisation." self.login() - managed_orgas = Organisation.objects.filter(is_managed=True) - self.assertEqual(1, len(managed_orgas)) - - managed_orga = managed_orgas[0] + managed_orga = self.get_alone_element(Organisation.objects.filter(is_managed=True)) self.assertPOST409(managed_orga.get_delete_absolute_url()) # follow=True self.assertStillExists(managed_orga) @@ -1041,10 +1038,7 @@ def test_set_orga_as_managed03(self): def test_set_orga_as_not_managed(self): self.login() - mngd_orgas = Organisation.objects.filter(is_managed=True) - self.assertEqual(1, len(mngd_orgas)) - - orga1 = mngd_orgas[0] + orga1 = self.get_alone_element(Organisation.objects.filter(is_managed=True)) orga2 = self._build_managed_orga() url = reverse('persons__orga_unset_managed') diff --git a/creme/persons/tests/organisation/test_merge.py b/creme/persons/tests/organisation/test_merge.py index 2920db3c7f..731cfacc59 100644 --- a/creme/persons/tests/organisation/test_merge.py +++ b/creme/persons/tests/organisation/test_merge.py @@ -249,10 +249,7 @@ def test_merge02(self): with self.assertNoException(): orga01 = self.refresh(orga01) - addresses = Address.objects.filter(object_id=orga01.id) - self.assertEqual(1, len(addresses)) - - address = addresses[0] + address = self.get_alone_element(Address.objects.filter(object_id=orga01.id)) self.assertEqual(orga01.billing_address, address) self.assertEqual(_('Billing address'), address.name) self.assertEqual('Merged address', address.address) diff --git a/creme/persons/tests/test_address.py b/creme/persons/tests/test_address.py index a52acac9ff..a89c8639f2 100644 --- a/creme/persons/tests/test_address.py +++ b/creme/persons/tests/test_address.py @@ -122,10 +122,7 @@ def test_createview(self): orga, name, address_value, po_box, city, state, zipcode, country, department, ) - addresses = Address.objects.filter(object_id=orga.id) - self.assertEqual(1, len(addresses)) - - address = addresses[0] + address = self.get_alone_element(Address.objects.filter(object_id=orga.id)) self.assertEqual(name, address.name) self.assertEqual(address_value, address.address) self.assertEqual(po_box, address.po_box) @@ -178,10 +175,7 @@ def test_create_billing01(self): }, )) - addresses = Address.objects.filter(object_id=orga.id) - self.assertEqual(1, len(addresses)) - - address = addresses[0] + address = self.get_alone_element(Address.objects.filter(object_id=orga.id)) self.assertEqual(city, address.city) self.assertEqual(addr_value, address.address) self.assertEqual('', address.po_box) @@ -222,10 +216,7 @@ def test_create_shipping(self): }, )) - addresses = Address.objects.filter(object_id=orga.id) - self.assertEqual(1, len(addresses)) - - address = addresses[0] + address = self.get_alone_element(Address.objects.filter(object_id=orga.id)) self.assertEqual(country, address.country) self.assertEqual(addr_value, address.address) self.assertEqual('', address.zipcode) diff --git a/creme/persons/tests/test_bricks.py b/creme/persons/tests/test_bricks.py index ce683f5e47..281871b989 100644 --- a/creme/persons/tests/test_bricks.py +++ b/creme/persons/tests/test_bricks.py @@ -783,10 +783,7 @@ def test_neglected_brick01(self): user = self.user bricks.NeglectedOrganisationsBrick() - orgas = Organisation.objects.all() - self.assertEqual(1, len(orgas)) - - mng_orga = orgas[0] + mng_orga = self.get_alone_element(Organisation.objects.all()) self.assertTrue(mng_orga.is_managed) self.assertFalse(self._get_neglected_orgas()) diff --git a/creme/persons/tests/test_buttons.py b/creme/persons/tests/test_buttons.py index 9460d287b9..00d34e54c6 100644 --- a/creme/persons/tests/test_buttons.py +++ b/creme/persons/tests/test_buttons.py @@ -19,10 +19,9 @@ class ButtonsTestCase(CremeTestCase): def test_become(self, button_class): user = self.create_user() - managed_orgas = [*Organisation.objects.filter_managed_by_creme().all()] - self.assertEqual(1, len(managed_orgas)) - - managed_orga = managed_orgas[0] + managed_orga = self.get_alone_element( + Organisation.objects.filter_managed_by_creme().all() + ) orga = Organisation.objects.create(user=user, name='Acme') button = button_class() @@ -41,10 +40,8 @@ def test_become_error(self): "Cannot link a managed organisation with itself." self.create_user() - managed_orgas = [*Organisation.objects.filter_managed_by_creme().all()] - self.assertEqual(1, len(managed_orgas)) - - managed_orga = managed_orgas[0] - + managed_orga = self.get_alone_element( + Organisation.objects.filter_managed_by_creme().all() + ) button = buttons.BecomeCustomerButton() self.assertFalse(button.ok_4_display(managed_orga)) diff --git a/creme/polls/tests/test_forms.py b/creme/polls/tests/test_forms.py index 37c990c1ef..bfa3476dce 100644 --- a/creme/polls/tests/test_forms.py +++ b/creme/polls/tests/test_forms.py @@ -109,10 +109,9 @@ def test_ok01(self): with self.assertNumQueries(0): field = PollFormLineConditionsField(sources=[line1, line2]) - conditions = field.clean(self.build_data({'source': line1.id, 'choice': 1})) - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element( + field.clean(self.build_data({'source': line1.id, 'choice': 1})) + ) self.assertIsInstance(condition, PollFormLineCondition) self.assertIsNone(condition.pk) self.assertEqual(line1, condition.source) diff --git a/creme/polls/tests/test_poll_form.py b/creme/polls/tests/test_poll_form.py index d5f7907af4..e95a71b937 100644 --- a/creme/polls/tests/test_poll_form.py +++ b/creme/polls/tests/test_poll_form.py @@ -289,10 +289,7 @@ def test_add_section01(self): # TODO: uniqueness of name ??? body = 'balabla' self.assertNoFormError(self.client.post(url, data={'name': name, 'body': body})) - sections = pform.sections.all() - self.assertEqual(1, len(sections)) - - section = sections[0] + section = self.get_alone_element(pform.sections.all()) self.assertIsInstance(section, PollFormSection) self.assertEqual(name, section.name) self.assertEqual(body, section.body) @@ -530,10 +527,7 @@ def test_add_line_string01(self): url, data={'question': question, 'type': qtype}, )) - lines = pform.lines.all() - self.assertEqual(1, len(lines)) - - line = lines[0] + line = self.get_alone_element(pform.lines.all()) self.assertIsInstance(line, PollFormLine) self.assertEqual(question, line.question) self.assertEqual(1, line.order) @@ -569,10 +563,7 @@ def test_add_line_text01(self): data={'question': question, 'type': qtype}, )) - lines = pform.lines.all() - self.assertEqual(1, len(lines)) - - line = lines[0] + line = self.get_alone_element(pform.lines.all()) self.assertIsInstance(line, PollFormLine) self.assertEqual(question, line.question) self.assertEqual(1, line.order) @@ -1632,10 +1623,7 @@ def test_add_line_conditions_enum01(self): self.assertIs(line2.conds_use_or, True) # self.assertEqual(ttype, line2.conds_type) # TODO - conditions = line2.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(line2.conditions.all()) self.assertEqual(line1, condition.source) self.assertEqual('1', condition.raw_answer) @@ -1757,10 +1745,7 @@ def test_add_line_conditions_bool(self, choice, raw_answer, error=None): else: self.assertNoFormError(response) - conditions = self.refresh(line2).conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(self.refresh(line2).conditions.all()) self.assertEqual(line1, condition.source) self.assertEqual(raw_answer, condition.raw_answer) @@ -1896,10 +1881,7 @@ def test_edit_line_conditions02(self): ) self.assertNoFormError(response) - conditions = line3.conditions.all() - self.assertEqual(1, len(conditions)) - - condition = conditions[0] + condition = self.get_alone_element(line3.conditions.all()) self.assertEqual(line1, condition.source) self.assertEqual('2', condition.raw_answer) diff --git a/creme/polls/tests/test_poll_reply.py b/creme/polls/tests/test_poll_reply.py index d9cbe723e0..72d8b211c6 100644 --- a/creme/polls/tests/test_poll_reply.py +++ b/creme/polls/tests/test_poll_reply.py @@ -957,10 +957,8 @@ def _aux_test_create_from_person(self, person): ) self.assertNoFormError(response) - replies = PollReply.objects.filter(pform=pform) - self.assertEqual(1, len(replies)) - - self.assertEqual(person.id, replies[0].person_id) + reply = self.get_alone_element(PollReply.objects.filter(pform=pform)) + self.assertEqual(person.id, reply.person_id) @skipIfCustomContact def test_create_from_person01(self): diff --git a/creme/products/tests/test_product.py b/creme/products/tests/test_product.py index 16044d20e5..072ea24a7f 100644 --- a/creme/products/tests/test_product.py +++ b/creme/products/tests/test_product.py @@ -190,10 +190,7 @@ def test_createview01(self): ) self.assertNoFormError(response3) - products = Product.objects.all() - self.assertEqual(1, len(products)) - - product = products[0] + product = self.get_alone_element(Product.objects.all()) self.assertEqual(name, product.name) self.assertEqual(code, product.code) self.assertEqual(description, product.description) diff --git a/creme/products/tests/test_service.py b/creme/products/tests/test_service.py index 8935210db5..ffe4591a81 100644 --- a/creme/products/tests/test_service.py +++ b/creme/products/tests/test_service.py @@ -74,10 +74,7 @@ def test_createview(self): ) self.assertNoFormError(response) - services = Service.objects.all() - self.assertEqual(1, len(services)) - - service = services[0] + service = self.get_alone_element(Service.objects.all()) self.assertEqual(name, service.name) self.assertEqual(reference, service.reference) self.assertEqual(description, service.description) diff --git a/creme/projects/tests.py b/creme/projects/tests.py index 056983cd6b..97106514fa 100644 --- a/creme/projects/tests.py +++ b/creme/projects/tests.py @@ -383,15 +383,12 @@ def test_listview_instance_actions(self): user = self.login() project = self.create_project('Eva00')[0] - project_actions = [ + close_action = self.get_alone_element( action for action in actions.actions_registry .instance_actions(user=user, instance=project) if isinstance(action, ProjectCloseAction) - ] - self.assertEqual(1, len(project_actions)) - - close_action = project_actions[0] + ) self.assertEqual('projects-close', close_action.type) self.assertEqual( reverse('projects__close_project', args=(project.id,)), @@ -410,15 +407,12 @@ def test_listview_instance_actions_closed(self): self.assertTrue(project.is_closed) - project_actions = [ + close_action = self.get_alone_element( action for action in actions.actions_registry .instance_actions(user=user, instance=project) if isinstance(action, ProjectCloseAction) - ] - self.assertEqual(1, len(project_actions)) - - close_action = project_actions[0] + ) self.assertEqual('projects-close', close_action.type) self.assertEqual( reverse('projects__close_project', args=(project.id,)), @@ -548,10 +542,7 @@ def post(duration): tasks = ProjectTask.objects.filter(linked_project=project) self.assertEqual(2, tasks.count()) - tasks2 = [t for t in tasks if t.id != task1.id] - self.assertEqual(1, len(tasks2)) - - task2 = tasks2[0] + task2 = self.get_alone_element(t for t in tasks if t.id != task1.id) self.assertListEqual([task1.id], [t.id for t in task2.parent_tasks.all()]) self.assertCountEqual(tasks, project.get_tasks()) @@ -835,9 +826,7 @@ def test_resource_n_activity01(self): worker = Contact.objects.create(user=user, first_name='Yui', last_name='Ikari') self.create_resource(task, worker, hourly_cost=100) - resources = [*task.resources_set.all()] - self.assertEqual(1, len(resources)) - resource = resources[0] + resource = self.get_alone_element(task.resources_set.all()) context = self.assertGET200(self._build_add_activity_url(task)).context self.assertEqual( @@ -928,10 +917,7 @@ def test_resource_n_activity02(self): resource = self.refresh(resource) self.assertEqual(200, resource.hourly_cost) - activities = task.related_activities - self.assertEqual(1, len(activities)) - - activity = activities[0] + activity = self.get_alone_element(task.related_activities) self.assertListEqual( [Calendar.objects.get_default_calendar(self.other_user)], [*activity.calendars.all()], @@ -1042,10 +1028,8 @@ def test_resource_n_activity05(self): 'type_selector': ACTIVITYSUBTYPE_MEETING_MEETING, } self.client.post(self._build_add_activity_url(task), follow=True, data=data) - activities = task.related_activities - self.assertEqual(1, len(activities)) - activity = activities[0] + activity = self.get_alone_element(task.related_activities) self.assertListEqual( [Calendar.objects.get_default_calendar(self.other_user)], [*activity.calendars.all()], @@ -1090,10 +1074,8 @@ def test_resource_n_activity06(self): 'type_selector': ACTIVITYSUBTYPE_MEETING_MEETING, } self.client.post(self._build_add_activity_url(task), follow=True, data=data) - activities = task.related_activities - self.assertEqual(1, len(activities)) + activity = self.get_alone_element(task.related_activities) - activity = activities[0] response = self.client.post( self._build_edit_activity_url(activity), follow=True, @@ -1301,9 +1283,7 @@ def test_edit_resource01(self): self.assertEqual(worker2, resource1.linked_contact) # activity of the resource => changes - activities1 = task1.related_activities - self.assertEqual(1, len(activities1)) - activity1 = activities1[0] + activity1 = self.get_alone_element(task1.related_activities) self.assertRelationCount(1, worker2, REL_SUB_PART_2_ACTIVITY, activity1) self.assertRelationCount(1, worker2, REL_SUB_PART_AS_RESOURCE, activity1) @@ -1317,9 +1297,7 @@ def test_edit_resource01(self): ) # activity of the other resource => no change - activities2 = task2.related_activities - self.assertEqual(1, len(activities2)) - activity2 = activities2[0] + activity2 = self.get_alone_element(task2.related_activities) self.assertRelationCount(1, worker1, REL_SUB_PART_2_ACTIVITY, activity2) self.assertRelationCount(1, worker1, REL_SUB_PART_AS_RESOURCE, activity2) @@ -1355,10 +1333,7 @@ def test_edit_resource02(self): resource1 = self.refresh(resource1) self.assertEqual(worker2, resource1.linked_contact) - activities = task.related_activities - self.assertEqual(1, len(activities)) - activity = activities[0] - + activity = self.get_alone_element(task.related_activities) self.assertRelationCount(1, worker2, REL_SUB_PART_2_ACTIVITY, activity) self.assertRelationCount(1, worker2, REL_SUB_PART_AS_RESOURCE, activity) diff --git a/creme/recurrents/tests/test_ticket.py b/creme/recurrents/tests/test_ticket.py index e45520da8f..438465449b 100644 --- a/creme/recurrents/tests/test_ticket.py +++ b/creme/recurrents/tests/test_ticket.py @@ -141,9 +141,8 @@ def test_createview(self): self.assertEqual(criticity, tpl.criticity) self.assertFalse(tpl.solution) - jobs = queue.refreshed_jobs - self.assertEqual(1, len(jobs)) - self.assertEqual(self._get_job(), jobs[0][0]) + job, _data = self.get_alone_element(queue.refreshed_jobs) + self.assertEqual(self._get_job(), job[0]) def test_editview01(self): user = self.user @@ -282,10 +281,7 @@ def test_job01(self): self._generate_docs(job) - new_tickets = Ticket.objects.all() - self.assertEqual(1, len(new_tickets)) - - ticket = new_tickets[0] + ticket = self.get_alone_element(Ticket.objects.all()) self.assertEqual( '{} {}'.format(tpl.title, date_format(now_value.date(), 'DATE_FORMAT')), ticket.title, diff --git a/creme/reports/tests/core/graph/test_aggregator.py b/creme/reports/tests/core/graph/test_aggregator.py index e0d7bc40c4..a41d281c75 100644 --- a/creme/reports/tests/core/graph/test_aggregator.py +++ b/creme/reports/tests/core/graph/test_aggregator.py @@ -188,20 +188,18 @@ def test_field_aggregation01(self): # --- cell1 = constraint.get_cell(cell_key='regular_field-capital') self.assertIsInstance(cell1, EntityCellRegularField) - finfo = cell1.field_info - self.assertEqual(1, len(finfo)) - self.assertEqual('capital', finfo[0].name) + finfo1 = cell1.field_info + self.assertEqual(1, len(finfo1)) + self.assertEqual('capital', finfo1[0].name) self.assertIsNone(constraint.get_cell(cell_key='regular_field-sector')) # --- - cells = [*constraint.cells()] - self.assertEqual(1, len(cells)) - - cell2 = cells[0] + cell2 = self.get_alone_element(constraint.cells()) self.assertIsInstance(cell2, EntityCellRegularField) - self.assertEqual(1, len(finfo)) - self.assertEqual('capital', finfo[0].name) + finfo2 = cell2.field_info + self.assertEqual(1, len(finfo2)) + self.assertEqual('capital', finfo2[0].name) def test_field_aggregation02(self): "Custom field." @@ -246,10 +244,7 @@ def test_field_aggregation02(self): self.assertIsNone(constraint.get_cell(cell_key=not_aggregable_cell.key)) # --- - cells = [*constraint.cells()] - self.assertEqual(1, len(cells)) - - cell2 = cells[0] + cell2 = self.get_alone_element(constraint.cells()) self.assertIsInstance(cell2, EntityCellCustomField) self.assertEqual(cfield1, cell2.custom_field) @@ -280,9 +275,7 @@ def test_field_aggregation03(self): descriptions=[(hidden_fname, {FieldsConfig.HIDDEN: True})], ) - cells1 = [*constraint.cells()] - self.assertEqual(1, len(cells1)) - cell1 = cells1[0] + cell1 = self.get_alone_element(constraint.cells()) self.assertIsInstance(cell1, EntityCellRegularField) self.assertEqual('total_vat', cell1.field_info[0].name) @@ -296,7 +289,7 @@ def test_field_aggregation03(self): ] self.assertSetEqual( {'total_vat', 'total_no_vat'}, - {cell.field_info[0].name for cell in cells3} + {cell.field_info[0].name for cell in cells3}, ) # --- @@ -343,9 +336,8 @@ def test_cell_constraints01(self): registry = AggregatorConstraintsRegistry( ).register_cell_constraints(ACCCount) - constraints = [*registry.cell_constraints(FakeInvoice)] - self.assertEqual(1, len(constraints)) - self.assertIsInstance(constraints[0], ACCCount) + constraint = self.get_alone_element(registry.cell_constraints(FakeInvoice)) + self.assertIsInstance(constraint, ACCCount) # --- get_constraint = registry.get_constraint_by_aggr_id diff --git a/creme/reports/tests/core/graph/test_cell_constraint.py b/creme/reports/tests/core/graph/test_cell_constraint.py index 37f3728314..1d32028e6d 100644 --- a/creme/reports/tests/core/graph/test_cell_constraint.py +++ b/creme/reports/tests/core/graph/test_cell_constraint.py @@ -300,16 +300,13 @@ def test_custom_enum(self): ) # --- - cells = [*constraint.cells()] - self.assertEqual(1, len(cells)) - - cell2 = cells[0] + cell2 = self.get_alone_element(constraint.cells()) self.assertIsInstance(cell2, EntityCellCustomField) self.assertEqual(cfield1, cell2.custom_field) self.assertListEqual( [key1, key4], - [c.key for c in constraint.cells(not_hiddable_cell_keys=[key4])] + [c.key for c in constraint.cells(not_hiddable_cell_keys=[key4])], ) def test_custom_date(self): @@ -337,10 +334,7 @@ def test_custom_date(self): self.assertIsNone(get_cell(cell_key=f'custom_field-{cfield3.id}')) # --- - cells = [*constraint.cells()] - self.assertEqual(1, len(cells)) - - cell2 = cells[0] + cell2 = self.get_alone_element(constraint.cells()) self.assertIsInstance(cell2, EntityCellCustomField) self.assertEqual(cfield1, cell2.custom_field) @@ -360,9 +354,8 @@ def test_cell_constraints01(self): rgraph_types=[AbscissaGroup.FK], ) - constraints = [*registry.cell_constraints(FakeContact)] - self.assertEqual(1, len(constraints)) - self.assertIsInstance(constraints[0], GHCCRegularFK) + constraint = self.get_alone_element(registry.cell_constraints(FakeContact)) + self.assertIsInstance(constraint, GHCCRegularFK) # --- get_constraint = registry.get_constraint_by_rgraph_type @@ -403,9 +396,8 @@ def test_cell_constraints03(self): rgraph_types=[AbscissaGroup.MONTH, AbscissaGroup.YEAR], ) - constraints = [*registry.cell_constraints(FakeContact)] - self.assertEqual(1, len(constraints)) # Not 2 - self.assertIsInstance(constraints[0], GHCCRegularDate) + constraint = self.get_alone_element(registry.cell_constraints(FakeContact)) # Not 2 + self.assertIsInstance(constraint, GHCCRegularDate) def test_cell_constraints04(self): "Duplicated constraints." diff --git a/creme/reports/tests/test_bricks.py b/creme/reports/tests/test_bricks.py index e011a528a4..adeedb9664 100644 --- a/creme/reports/tests/test_bricks.py +++ b/creme/reports/tests/test_bricks.py @@ -559,10 +559,9 @@ def test_add_graph_instance_brick01(self): self.assertNoFormError(self.client.post(url, data={'fetcher': RGF_NOLINK})) - items = InstanceBrickConfigItem.objects.filter(entity=rgraph.id) - self.assertEqual(1, len(items)) - - item = items[0] + item = self.get_alone_element( + InstanceBrickConfigItem.objects.filter(entity=rgraph.id) + ) self.assertEqual('instanceblock_reports-graph', item.brick_class_id) self.assertEqual(RGF_NOLINK, item.get_extra_data('type')) self.assertIsNone(item.get_extra_data('value')) @@ -705,10 +704,9 @@ def test_add_graph_instance_brick02(self): self.assertNoFormError(self.client.post(url, data={'fetcher': folder_choice})) - items = InstanceBrickConfigItem.objects.filter(entity=rgraph.id) - self.assertEqual(1, len(items)) - - item = items[0] + item = self.get_alone_element( + InstanceBrickConfigItem.objects.filter(entity=rgraph.id) + ) self.assertEqual('instanceblock_reports-graph', item.brick_class_id) self.assertEqual(RGF_FK, item.get_extra_data('type')) self.assertEqual(fk_name, item.get_extra_data('value')) @@ -867,10 +865,9 @@ def test_add_graph_instance_brick03(self): self.assertNoFormError(self.client.post(url, data={'fetcher': choice_id})) - items = InstanceBrickConfigItem.objects.filter(entity=rgraph.id) - self.assertEqual(1, len(items)) - - item = items[0] + item = self.get_alone_element( + InstanceBrickConfigItem.objects.filter(entity=rgraph.id) + ) self.assertEqual('instanceblock_reports-graph', item.brick_class_id) self.assertEqual(RGF_RELATION, item.get_extra_data('type')) self.assertEqual(rtype.id, item.get_extra_data('value')) diff --git a/creme/reports/tests/test_graph.py b/creme/reports/tests/test_graph.py index cd2903e686..6ebfe24e93 100644 --- a/creme/reports/tests/test_graph.py +++ b/creme/reports/tests/test_graph.py @@ -3120,10 +3120,9 @@ def test_clone_report(self): cloned_report = report.clone() - rgrahes = ReportGraph.objects.filter(linked_report=cloned_report) - self.assertEqual(1, len(rgrahes)) - - cloned_rgraph = rgrahes[0] + cloned_rgraph = self.get_alone_element( + ReportGraph.objects.filter(linked_report=cloned_report) + ) self.assertNotEqual(rgraph.id, cloned_rgraph.id) self.assertEqual(rgraph.name, cloned_rgraph.name) diff --git a/creme/reports/tests/test_report.py b/creme/reports/tests/test_report.py index d3fa24242c..3dcf51dcf4 100644 --- a/creme/reports/tests/test_report.py +++ b/creme/reports/tests/test_report.py @@ -894,15 +894,12 @@ def test_listview_actions(self): user = self.login() report = self._create_simple_contacts_report('Report#1') - export_actions = [ + export_action = self.get_alone_element( action for action in actions.actions_registry .instance_actions(user=user, instance=report) if isinstance(action, ExportReportAction) - ] - self.assertEqual(1, len(export_actions)) - - export_action = export_actions[0] + ) self.assertEqual('reports-export', export_action.id) self.assertEqual('reports-export', export_action.type) self.assertEqual( diff --git a/creme/sms/tests/test_sending.py b/creme/sms/tests/test_sending.py index 716809ad5d..550ded6026 100644 --- a/creme/sms/tests/test_sending.py +++ b/creme/sms/tests/test_sending.py @@ -100,10 +100,7 @@ def test_create01(self): data={'template': template.id}, )) - sendings = self.refresh(camp).sendings.all() - self.assertEqual(1, len(sendings)) - - sending = sendings[0] + sending = self.get_alone_element(self.refresh(camp).sendings.all()) self.assertEqual(date.today(), sending.date) self.assertEqual(template, sending.template) self.assertEqual('SUBJECT : BODYYYYYYYYYYY', sending.content) diff --git a/creme/tickets/tests.py b/creme/tickets/tests.py index 745ac8c06e..4bb40d450e 100644 --- a/creme/tickets/tests.py +++ b/creme/tickets/tests.py @@ -274,15 +274,13 @@ def test_number(self): criticity=Criticity.objects.all()[0], ) ticket1 = create_ticket(title='Test ticket #1') - numbers1 = TicketNumber.objects.all() - self.assertEqual(1, len(numbers1)) - self.assertEqual(numbers1[0].id, ticket1.number) + number1 = self.get_alone_element(TicketNumber.objects.all()) + self.assertEqual(number1.id, ticket1.number) ticket2 = create_ticket(title='Test ticket #2') self.assertNotEqual(ticket1.number, ticket2.number) - numbers2 = TicketNumber.objects.all() - self.assertEqual(1, len(numbers2)) + self.get_alone_element(TicketNumber.objects.all()) def test_get_resolving_duration01(self): "Resolving duration with CLOSED_PK + closing_date=None (e.g. CSV import)." diff --git a/creme/vcfs/tests/test_app.py b/creme/vcfs/tests/test_app.py index 944ed54ac9..92a603f283 100644 --- a/creme/vcfs/tests/test_app.py +++ b/creme/vcfs/tests/test_app.py @@ -27,14 +27,11 @@ def test_config(self): def test_actions(self): user = self.login() contact = user.linked_contact - vcfs_actions = [ + action = self.get_alone_element( action for action in actions_registry.instance_actions(user=user, instance=contact) if isinstance(action, GenerateVcfAction) - ] - self.assertEqual(1, len(vcfs_actions)) - - action = vcfs_actions[0] + ) self.assertEqual('redirect', action.type) self.assertEqual(reverse('vcfs__export', args=(contact.id,)), action.url) self.assertTrue(action.is_enabled) # TODO: test with credentials diff --git a/creme/vcfs/tests/test_import.py b/creme/vcfs/tests/test_import.py index 14f346cd9f..ae7a9fc606 100644 --- a/creme/vcfs/tests/test_import.py +++ b/creme/vcfs/tests/test_import.py @@ -1604,17 +1604,17 @@ def test_vcf_with_image03(self): with self.assertNoException(): errors = response2.context['form'].errors['image_encoded'] - self.assertEqual(1, len(errors)) + error = self.get_alone_element(errors) self.assertEqual( _( 'An error occurred when trying to retrieve the referenced ' 'image [original error: {}].' ).format(exception), - errors[0], + error, ) # self.assertEqual(contact_count + 1, Contact.objects.count()) - self.assertEqual(image_count, Document.objects.count()) + self.assertEqual(image_count, Document.objects.count()) @override_settings(VCF_IMAGE_MAX_SIZE=10240) # (10 kB) def test_vcf_with_image04(self):