class TestDeleteDomain(TestCase): def _create_data(self, domain_name): product = Product(domain=domain_name, name="test-product") product.save() location = Location(domain=domain_name, site_code="testcode", name="test1", location_type="facility") location.save() self.locations[domain_name] = location.sql_location user = CommCareUser.create(domain=domain_name, username="******".format(domain_name), password="******") FacilityInCharge.objects.create(user_id=user.get_id, location=location.sql_location) def setUp(self): self.domain = Domain(name="test", is_active=True) self.domain.save() self.domain2 = Domain(name="test2", is_active=True) self.domain2.save() self.locations = {} LocationType.objects.create(domain="test", name="facility") LocationType.objects.create(domain="test2", name="facility") self._create_data("test") self._create_data("test2") def test_pre_delete_signal_receiver(self): self.domain.delete() self.assertEqual(FacilityInCharge.objects.filter(location=self.locations["test"]).count(), 0) self.assertEqual(FacilityInCharge.objects.filter(location=self.locations["test2"]).count(), 1) def tearDown(self): self.domain2.delete()
class DomainCopyTest(TestCase): def setUp(self): self.domain = Domain(name='test') self.domain.save() app = Application.new_app('test', "Test Application", lang='en', application_version=APP_V2) module = Module.new_module("Untitled Module", 'en') app.add_module(module) app.new_form(0, "Untitled Form", 'en') app.save() def tearDown(self): self.domain.delete() def test_base(self): new_domain = self.domain.save_copy() new_domain.delete() def test_usercase_enabled(self): self.domain.usercase_enabled = True self.domain.save() new_domain = self.domain.save_copy() new_domain.delete()
class TestSubscriptionChangeResourceConflict(BaseAccountingTest): def setUp(self): self.domain_name = 'test-domain-changes' self.domain = Domain( name=self.domain_name, is_active=True, description='spam', ) self.domain.save() def tearDown(self): self.domain.delete() super(TestSubscriptionChangeResourceConflict, self).tearDown() def test_domain_changes(self): role = Mock() role.memberships_granted.all.return_value = [] version = Mock() version.role.get_cached_role.return_value = role handler = DomainDowngradeActionHandler( self.domain, new_plan_version=version, changed_privs=REPORT_BUILDER_ADD_ON_PRIVS) conflicting_domain = Domain.get_by_name(self.domain_name) conflicting_domain.description = 'eggs' conflicting_domain.save() get_by_name_func = Domain.get_by_name with patch('corehq.apps.accounting.subscription_changes.Domain' ) as Domain_patch: Domain_patch.get_by_name.side_effect = lambda name: get_by_name_func( name) handler.get_response() Domain_patch.get_by_name.assert_called_with(self.domain_name)
class BaseReminderTestCase(BaseAccountingTest): def setUp(self): super(BaseReminderTestCase, self).setUp() self.domain_obj = Domain(name="test") self.domain_obj.save() # Prevent resource conflict self.domain_obj = Domain.get(self.domain_obj._id) self.account, _ = BillingAccount.get_or_create_account_by_domain( self.domain_obj.name, created_by="tests" ) advanced_plan_version = DefaultProductPlan.get_default_plan_by_domain( self.domain_obj, edition=SoftwarePlanEdition.ADVANCED) self.subscription = Subscription.new_domain_subscription( self.account, self.domain_obj.name, advanced_plan_version ) self.subscription.is_active = True self.subscription.save() self.sms_backend = TestSMSBackend(named="MOBILE_BACKEND_TEST", is_global=True) self.sms_backend.save() self.sms_backend_mapping = BackendMapping(is_global=True,prefix="*",backend_id=self.sms_backend._id) self.sms_backend_mapping.save() def tearDown(self): self.sms_backend_mapping.delete() self.sms_backend.delete() SubscriptionAdjustment.objects.all().delete() self.subscription.delete() self.account.delete() self.domain_obj.delete()
class DomainCalculatedPropertiesTest(TestCase): @classmethod def setUpClass(cls): super(DomainCalculatedPropertiesTest, cls).setUpClass() cls.es = [{ 'info': i, 'instance': get_es_new(), } for i in [CASE_INDEX_INFO, SMS_INDEX_INFO, XFORM_INDEX_INFO]] def setUp(self): self.domain = Domain(name='test-b9289e19d819') self.domain.save() for es in self.es: ensure_index_deleted(es['info'].index) initialize_index_and_mapping(es['instance'], es['info']) def tearDown(self): self.domain.delete() def test_sanity(self): all_stats = all_domain_stats() props = calced_props(self.domain, self.domain._id, all_stats) self.assertFalse(props['cp_has_app']) # ensure serializable json.dumps(props)
class OtaV3RestoreTest(TestCase): """Tests OTA Restore v3""" def setUp(self): self.domain = 'dummy-project' self.project = Domain(name=self.domain) self.project.save() delete_all_cases() delete_all_sync_logs() delete_all_users() def tearDown(self): self.project.delete() def testUserRestoreWithCase(self): restore_user = create_restore_user(domain=self.domain) expected_case_block = CaseBlock( create=True, case_id='my-case-id', user_id=restore_user.user_id, owner_id=restore_user.user_id, case_type='test-case-type', update={'external_id': 'someexternal'}, ) _, [case] = post_case_blocks([expected_case_block.as_xml()], {'domain': self.domain}) assert_user_has_case(self, restore_user, case.case_id)
class OtaV3RestoreTest(TestCase): """Tests OTA Restore v3""" def setUp(self): self.domain = 'dummy-project' self.project = Domain(name=self.domain) self.project.save() delete_all_cases() delete_all_sync_logs() delete_all_users() def tearDown(self): self.project.delete() def testUserRestoreWithCase(self): restore_user = create_restore_user(domain=self.domain) case_id = 'my-case-id' device = MockDevice(self.project, restore_user) device.change_cases(CaseBlock( create=True, case_id=case_id, user_id=restore_user.user_id, owner_id=restore_user.user_id, case_type='test-case-type', update={'external_id': 'someexternal'}, )) self.assertIn(case_id, device.sync().cases)
class TestSubscriptionChangeResourceConflict(BaseAccountingTest): def setUp(self): self.domain_name = 'test-domain-changes' self.domain = Domain( name=self.domain_name, is_active=True, description='spam', ) self.domain.save() def tearDown(self): self.domain.delete() super(TestSubscriptionChangeResourceConflict, self).tearDown() def test_domain_changes(self): role = Mock() role.memberships_granted.all.return_value = [] version = Mock() version.role.get_cached_role.return_value = role handler = DomainDowngradeActionHandler( self.domain, new_plan_version=version, changed_privs=REPORT_BUILDER_ADD_ON_PRIVS ) conflicting_domain = Domain.get_by_name(self.domain_name) conflicting_domain.description = 'eggs' conflicting_domain.save() get_by_name_func = Domain.get_by_name with patch('corehq.apps.accounting.subscription_changes.Domain') as Domain_patch: Domain_patch.get_by_name.side_effect = lambda name: get_by_name_func(name) handler.get_response() Domain_patch.get_by_name.assert_called_with(self.domain_name)
class BaseDomainTest(TestCase): def setUp(self): self.client = Client() self.domain = Domain(name="fandago", is_active=True) self.domain.save() toggles.TRANSFER_DOMAIN.set("domain:{domain}".format(domain=self.domain.name), True) self.username = '******' self.password = '******' self.user = WebUser.create(self.domain.name, self.username, self.password) self.user.set_role(self.domain.name, 'admin') self.user.save() self.another_domain = Domain(name='anotherdomain', is_active=True) self.another_domain.save() self.mugglename = 'muggle' self.muggle = WebUser.create(self.another_domain.name, self.mugglename, self.password) self.muggle.save() def tearDown(self): self.user.delete() self.domain.delete() self.muggle.delete() self.another_domain.delete()
class DomainCopyTest(TestCase): def setUp(self): self.domain = Domain(name='test') self.domain.save() app = Application.new_app( 'test', "Test Application", lang='en', application_version=APP_V2 ) module = Module.new_module("Untitled Module", 'en') app.add_module(module) app.new_form(0, "Untitled Form", 'en') app.save() def tearDown(self): self.domain.delete() def test_base(self): new_domain = self.domain.save_copy() new_domain.delete() def test_usercase_enabled(self): self.domain.usercase_enabled = True self.domain.save() new_domain = self.domain.save_copy() new_domain.delete()
class TestExpandedMobileWorkerFilter(TestCase): def setUp(self): clear_domain_names('test') self.domain = Domain(name='test', is_active=True) self.domain.save() self.location_type = LocationType.objects.create( domain=self.domain.name, name='testtype') self.user_assigned_locations = [ make_loc('root', domain=self.domain.name, type=self.location_type.code).sql_location ] self.request = RequestFactory() self.request.couch_user = WebUser() self.request.domain = self.domain def tearDown(self): self.domain.delete() super().tearDown() @patch('corehq.apps.users.models.WebUser.get_sql_locations') def test_get_assigned_locations_default(self, assigned_locations_patch): assigned_locations_patch.return_value = self.user_assigned_locations emwf = ExpandedMobileWorkerFilter(self.request) loc_defaults = emwf._get_assigned_locations_default() self.assertEqual( loc_defaults, list(map(emwf.utils.location_tuple, self.user_assigned_locations)))
class DeviceIdUpdateTest(ENikshayCaseStructureMixin, TestCase): def setUp(self): super(DeviceIdUpdateTest, self).setUp() self.domain_obj = Domain(name=self.domain) self.domain_obj.save() self.web_user_username = "******" self.web_user_password = "******" self.web_user = WebUser.create( self.domain, username=self.web_user_username, password=self.web_user_password, ) def tearDown(self): self.domain_obj.delete() super(DeviceIdUpdateTest, self).tearDown() def test_login_as(self): self.web_user.is_superuser = True self.web_user.save() restore_uri = reverse('ota_restore', args=[self.domain]) auth_header = _get_auth_header(self.web_user_username, self.web_user_password) client = Client(HTTP_AUTHORIZATION=auth_header) device_id = "foo" resp = client.get(restore_uri, data={'as': self.username, "device_id": device_id}, follow=True) self.assertEqual(resp.status_code, 200) restored_as_user = CommCareUser.get_by_username(self.username) self.assertEqual(len(restored_as_user.devices), 1) self.assertEqual(restored_as_user.devices[0].device_id, device_id)
class AllCommCareUsersTest(TestCase): def setUp(self): self.ccdomain = Domain(name="cc_user_domain") self.ccdomain.save() self.other_domain = Domain(name="other_domain") self.other_domain.save() self.ccuser_1 = CommCareUser.create( domain=self.ccdomain.name, username="******", password="******", email="*****@*****.**" ) self.ccuser_2 = CommCareUser.create( domain=self.ccdomain.name, username="******", password="******", email="*****@*****.**" ) self.web_user = WebUser.create( domain=self.ccdomain.name, username="******", password="******", email="*****@*****.**" ) self.ccuser_other_domain = CommCareUser.create( domain=self.other_domain.name, username="******", password="******", email="*****@*****.**", ) def tearDown(self): self.ccdomain.delete() self.other_domain.delete() def test_get_all_commcare_users_by_domain(self): expected_users = [self.ccuser_2, self.ccuser_1] expected_usernames = [user.username for user in expected_users] actual_usernames = [user.username for user in get_all_commcare_users_by_domain(self.ccdomain.name)] self.assertItemsEqual(actual_usernames, expected_usernames)
class TestSubscription(BaseAccountingTest): def setUp(self): super(TestSubscription, self).setUp() self.billing_contact = generator.arbitrary_web_user() self.dimagi_user = generator.arbitrary_web_user(is_dimagi=True) self.domain = Domain(name='test') self.domain.save() self.currency = generator.init_default_currency() self.account = generator.billing_account(self.dimagi_user, self.billing_contact) self.subscription, self.subscription_length = generator.generate_domain_subscription_from_date( datetime.date.today(), self.account, self.domain.name ) def test_creation(self): self.assertIsNotNone(self.subscription) def test_no_activation(self): tasks.activate_subscriptions(based_on_date=self.subscription.date_start - datetime.timedelta(30)) subscription = Subscription.objects.get(id=self.subscription.id) self.assertFalse(subscription.is_active) def test_activation(self): tasks.activate_subscriptions(based_on_date=self.subscription.date_start) subscription = Subscription.objects.get(id=self.subscription.id) self.assertTrue(subscription.is_active) def test_no_deactivation(self): tasks.activate_subscriptions(based_on_date=self.subscription.date_start) tasks.deactivate_subscriptions(based_on_date=self.subscription.date_end - datetime.timedelta(30)) subscription = Subscription.objects.get(id=self.subscription.id) self.assertTrue(subscription.is_active) def test_deactivation(self): tasks.deactivate_subscriptions(based_on_date=self.subscription.date_end) subscription = Subscription.objects.get(id=self.subscription.id) self.assertFalse(subscription.is_active) def test_deletions(self): self.assertRaises(models.ProtectedError, self.account.delete) self.assertRaises(models.ProtectedError, self.subscription.plan_version.delete) self.assertRaises(models.ProtectedError, self.subscription.subscriber.delete) def test_is_hidden_to_ops(self): self.subscription.is_hidden_to_ops = True self.subscription.save() self.assertEqual(0, len(Subscription.objects.filter(id=self.subscription.id))) self.subscription.is_hidden_to_ops = False self.subscription.save() self.assertEqual(1, len(Subscription.objects.filter(id=self.subscription.id))) def tearDown(self): self.billing_contact.delete() self.dimagi_user.delete() self.domain.delete() generator.delete_all_subscriptions() generator.delete_all_accounts() super(TestSubscription, self).tearDown()
class BaseDomainTest(TestCase): def setUp(self): self.client = Client() self.domain = Domain(name="fandago", is_active=True) self.domain.save() toggles.TRANSFER_DOMAIN.set( "domain:{domain}".format(domain=self.domain.name), True) self.username = '******' self.password = '******' self.user = WebUser.create(self.domain.name, self.username, self.password, None, None) self.user.set_role(self.domain.name, 'admin') self.user.save() self.another_domain = Domain(name='anotherdomain', is_active=True) self.another_domain.save() self.mugglename = 'muggle' self.muggle = WebUser.create(self.another_domain.name, self.mugglename, self.password, None, None) self.muggle.save() def tearDown(self): self.user.delete() self.domain.delete() self.muggle.delete() self.another_domain.delete()
class TestDomainViews(TestCase): def setUp(self): self.client = Client() self.domain = Domain(name="fandago", is_active=True) self.domain.save() self.username = '******' self.password = '******' self.user = WebUser.create(self.domain.name, self.username, self.password) self.user.set_role(self.domain.name, 'admin') self.user.save() def tearDown(self): self.user.delete() self.domain.delete() def test_add_repeater(self): forwarding_url = 'https://example.com/forwarding' self.client.login(username=self.username, password=self.password) post_url = reverse('add_repeater', kwargs={'domain': self.domain.name, 'repeater_type': 'AppStructureRepeater'}) response = self.client.post(post_url, {'url': forwarding_url}, follow=True) self.assertEqual(response.status_code, 200) self.client.logout() app_structure_repeaters = AppStructureRepeater.by_domain(self.domain.name) self.assertEqual(len(app_structure_repeaters), 1) for app_structure_repeater in app_structure_repeaters: app_structure_repeater.delete()
class TestBillingRecord(BaseAccountingTest): def setUp(self): super(TestBillingRecord, self).setUp() self.billing_contact = generator.create_arbitrary_web_user_name() self.dimagi_user = generator.create_arbitrary_web_user_name( is_dimagi=True) self.domain = Domain(name='test') self.domain.save() self.invoice_start, self.invoice_end = get_previous_month_date_range() self.currency = generator.init_default_currency() self.account = generator.billing_account(self.dimagi_user, self.billing_contact) self.subscription_length = 4 # months subscription_start_date = datetime.date(2016, 2, 23) subscription_end_date = add_months_to_date(subscription_start_date, self.subscription_length) self.subscription = generator.generate_domain_subscription( self.account, self.domain, date_start=subscription_start_date, date_end=subscription_end_date, ) self.invoice = Invoice( subscription=self.subscription, date_start=self.invoice_start, date_end=self.invoice_end, is_hidden=False, ) self.billing_record = BillingRecord(invoice=self.invoice) def tearDown(self): self.domain.delete() super(TestBillingRecord, self).tearDown() def test_should_send_email(self): self.assertTrue(self.billing_record.should_send_email) def test_should_send_email_contracted(self): self.subscription.service_type = SubscriptionType.IMPLEMENTATION self.assertFalse(self.billing_record.should_send_email) self.invoice.balance = Decimal(SMALL_INVOICE_THRESHOLD - 1) self.assertFalse(self.billing_record.should_send_email) self.invoice.balance = Decimal(SMALL_INVOICE_THRESHOLD + 1) self.assertTrue(self.billing_record.should_send_email) def test_should_send_email_autogenerate_credits(self): self.subscription.auto_generate_credits = True self.assertFalse(self.billing_record.should_send_email) self.invoice.balance = Decimal(SMALL_INVOICE_THRESHOLD + 1) self.assertTrue(self.billing_record.should_send_email) def test_should_send_email_hidden(self): self.assertTrue(self.billing_record.should_send_email) self.invoice.is_hidden = True self.assertFalse(self.billing_record.should_send_email)
class DomainCalculatedPropertiesTest(TestCase): @classmethod def setUpClass(cls): super(DomainCalculatedPropertiesTest, cls).setUpClass() cls.es = [{ 'info': i, 'instance': get_es_new(), } for i in [CASE_INDEX_INFO, SMS_INDEX_INFO, XFORM_INDEX_INFO]] def setUp(self): self.domain = Domain(name='test') self.domain.save() for es in self.es: ensure_index_deleted(es['info'].index) initialize_index_and_mapping(es['instance'], es['info']) def tearDown(self): self.domain.delete() def test_sanity(self): all_stats = all_domain_stats() props = calced_props(self.domain.name, self.domain._id, all_stats) self.assertFalse(props['cp_has_app']) # ensure serializable json.dumps(props)
class IncomingPostTest(TestCase): INDIA_TZ_OFFSET = timedelta(hours=5.5) @classmethod def setUpClass(cls): super(IncomingPostTest, cls).setUpClass() cls.unicel_backend = SQLUnicelBackend.objects.create( name='UNICEL', is_global=True, hq_api_id=SQLUnicelBackend.get_api_id() ) @classmethod def tearDownClass(cls): cls.unicel_backend.delete() super(IncomingPostTest, cls).tearDownClass() def setUp(self): super().setUp() self.domain = Domain(name='mockdomain') self.domain.save() SMS.by_domain(self.domain.name).delete() self.user = '******' self.password = '******' self.number = 5555551234 self.couch_user = WebUser.create(self.domain.name, self.user, self.password, None, None) self.couch_user.add_phone_number(self.number) self.couch_user.save() self.message_ascii = 'It Works' self.message_utf_hex = '0939093F0928094D092609400020091509300924093E00200939094800200907093800200938092E092F00200915093E092E002009390948003F' def tearDown(self): self.couch_user.delete(self.domain.name, deleted_by=None) self.domain.delete() super().tearDown() def testPostToIncomingAscii(self): fake_post = {InboundParams.SENDER: str(self.number), InboundParams.MESSAGE: self.message_ascii, InboundParams.MID: '00001', InboundParams.DCS: '0'} response, log = post(fake_post, self.unicel_backend) self.assertEqual(200, response.status_code) self.assertEqual(self.message_ascii, log.text) self.assertEqual(INCOMING, log.direction) self.assertEqual(log.backend_message_id, fake_post[InboundParams.MID]) def testPostToIncomingUtf(self): fake_post = {InboundParams.SENDER: str(self.number), InboundParams.MESSAGE: self.message_utf_hex, InboundParams.MID: '00002', InboundParams.DCS: '8'} response, log = post(fake_post, self.unicel_backend) self.assertEqual(200, response.status_code) self.assertEqual(codecs.decode(codecs.decode(self.message_utf_hex, 'hex'), 'utf_16_be'), log.text) self.assertEqual(INCOMING, log.direction) self.assertEqual(log.backend_message_id, fake_post[InboundParams.MID])
class TestBillingRecord(BaseAccountingTest): def setUp(self): super(TestBillingRecord, self).setUp() self.billing_contact = generator.create_arbitrary_web_user_name() self.dimagi_user = generator.create_arbitrary_web_user_name(is_dimagi=True) self.domain = Domain(name='test') self.domain.save() self.invoice_start, self.invoice_end = get_previous_month_date_range() self.currency = generator.init_default_currency() self.account = generator.billing_account(self.dimagi_user, self.billing_contact) self.subscription_length = 4 # months subscription_start_date = datetime.date(2016, 2, 23) subscription_end_date = add_months_to_date(subscription_start_date, self.subscription_length) self.subscription = generator.generate_domain_subscription( self.account, self.domain, date_start=subscription_start_date, date_end=subscription_end_date, ) self.invoice = Invoice( subscription=self.subscription, date_start=self.invoice_start, date_end=self.invoice_end, is_hidden=False, ) self.billing_record = BillingRecord(invoice=self.invoice) def tearDown(self): self.domain.delete() super(TestBillingRecord, self).tearDown() def test_should_send_email(self): self.assertTrue(self.billing_record.should_send_email) def test_should_send_email_contracted(self): self.subscription.service_type = SubscriptionType.IMPLEMENTATION self.assertFalse(self.billing_record.should_send_email) self.invoice.balance = Decimal(SMALL_INVOICE_THRESHOLD - 1) self.assertFalse(self.billing_record.should_send_email) self.invoice.balance = Decimal(SMALL_INVOICE_THRESHOLD + 1) self.assertTrue(self.billing_record.should_send_email) def test_should_send_email_autogenerate_credits(self): self.subscription.auto_generate_credits = True self.assertFalse(self.billing_record.should_send_email) self.invoice.balance = Decimal(SMALL_INVOICE_THRESHOLD + 1) self.assertTrue(self.billing_record.should_send_email) def test_should_send_email_hidden(self): self.assertTrue(self.billing_record.should_send_email) self.invoice.is_hidden = True self.assertFalse(self.billing_record.should_send_email)
class IncomingPostTest(TestCase): INDIA_TZ_OFFSET = timedelta(hours=5.5) @classmethod def setUpClass(cls): super(IncomingPostTest, cls).setUpClass() cls.unicel_backend = SQLUnicelBackend.objects.create( name='UNICEL', is_global=True, hq_api_id=SQLUnicelBackend.get_api_id() ) @classmethod def tearDownClass(cls): cls.unicel_backend.delete() super(IncomingPostTest, cls).tearDownClass() def setUp(self): self.domain = Domain(name='mockdomain') self.domain.save() SMS.by_domain(self.domain.name).delete() self.user = '******' self.password = '******' self.number = 5555551234 self.couch_user = WebUser.create(self.domain.name, self.user, self.password) self.couch_user.add_phone_number(self.number) self.couch_user.save() self.message_ascii = 'It Works' self.message_utf_hex = '0939093F0928094D092609400020091509300924093E00200939094800200907093800200938092E092F00200915093E092E002009390948003F' def tearDown(self): self.couch_user.delete() self.domain.delete() def testPostToIncomingAscii(self): fake_post = {InboundParams.SENDER: str(self.number), InboundParams.MESSAGE: self.message_ascii, InboundParams.MID: '00001', InboundParams.DCS: '0'} response, log = post(fake_post, self.unicel_backend) self.assertEqual(200, response.status_code) self.assertEqual(self.message_ascii, log.text) self.assertEqual(INCOMING, log.direction) self.assertEqual(log.backend_message_id, fake_post[InboundParams.MID]) def testPostToIncomingUtf(self): fake_post = {InboundParams.SENDER: str(self.number), InboundParams.MESSAGE: self.message_utf_hex, InboundParams.MID: '00002', InboundParams.DCS: '8'} response, log = post(fake_post, self.unicel_backend) self.assertEqual(200, response.status_code) self.assertEqual(codecs.decode(codecs.decode(self.message_utf_hex, 'hex'), 'utf_16_be'), log.text) self.assertEqual(INCOMING, log.direction) self.assertEqual(log.backend_message_id, fake_post[InboundParams.MID])
def domain_fixture(domain_name, allow_domain_requests=False): domain = Domain(name=domain_name, is_active=True) if allow_domain_requests: domain.allow_domain_requests = True domain.save() try: yield finally: domain.delete()
def test_disallow_domain_requests(self): self.client.login(username=self.username, password=self.password) private_domain = Domain(name="private", is_active=True) private_domain.save() response = self.client.get(reverse("domain_homepage", args=[private_domain.name]), follow=True) self.assertEqual(response.status_code, 404) private_domain.delete()
class OptTestCase(BaseAccountingTest): def setUp(self): super(OptTestCase, self).setUp() self.domain = "opt-test" self.domain_obj = Domain(name=self.domain) self.domain_obj.save() generator.instantiate_accounting_for_tests() self.account = BillingAccount.get_or_create_account_by_domain( self.domain_obj.name, created_by="automated-test" )[0] plan = DefaultProductPlan.get_default_plan_by_domain(self.domain_obj, edition=SoftwarePlanEdition.ADVANCED) self.subscription = Subscription.new_domain_subscription(self.account, self.domain_obj.name, plan) self.subscription.is_active = True self.subscription.save() self.backend = TestSMSBackend(is_global=True) self.backend.save() self.backend_mapping = BackendMapping(is_global=True, prefix="*", backend_id=self.backend._id) self.backend_mapping.save() def test_opt_out_and_opt_in(self): self.assertEqual(PhoneNumber.objects.count(), 0) incoming("99912345678", "stop", "GVI") self.assertEqual(PhoneNumber.objects.count(), 1) phone_number = PhoneNumber.objects.get(phone_number="99912345678") self.assertFalse(phone_number.send_sms) incoming("99912345678", "start", "GVI") self.assertEqual(PhoneNumber.objects.count(), 1) phone_number = PhoneNumber.objects.get(phone_number="99912345678") self.assertTrue(phone_number.send_sms) def test_sending_to_opted_out_number(self): self.assertEqual(PhoneNumber.objects.count(), 0) self.assertTrue(send_sms(self.domain, None, "999123456789", "hello")) incoming("999123456789", "stop", "GVI") self.assertEqual(PhoneNumber.objects.count(), 1) phone_number = PhoneNumber.objects.get(phone_number="999123456789") self.assertFalse(phone_number.send_sms) self.assertFalse(send_sms(self.domain, None, "999123456789", "hello")) def tearDown(self): self.backend_mapping.delete() self.backend.delete() self.domain_obj.delete() SubscriptionAdjustment.objects.all().delete() self.subscription.delete() self.account.delete()
class TestUserBulkUploadStrongPassword(TestCase, DomainSubscriptionMixin): def setUp(self): super(TestUserBulkUploadStrongPassword, self).setUp() delete_all_users() self.domain_name = 'mydomain' self.domain = Domain(name=self.domain_name) self.domain.strong_mobile_passwords = True self.domain.save() self.user_specs = [{ 'username': '******', 'user_id': '1989', 'name': 'Taylor Swift', 'language': None, 'is_active': 'True', 'phone-number': '8675309', 'password': '******', 'email': None }] def tearDown(self): self.domain.delete() super(TestUserBulkUploadStrongPassword, self).tearDown() def test_duplicate_password(self): user_spec = [{ 'username': '******', 'user_id': '1990', 'name': 'Tom Hiddleston', 'language': None, 'is_active': 'True', 'phone-number': '8675309', 'password': '******', 'email': None }] rows = import_users_and_groups( self.domain.name, list(user_spec + self.user_specs), [], )['messages']['rows'] self.assertEqual(rows[0]['flag'], "'password' values must be unique") def test_weak_password(self): updated_user_spec = deepcopy(self.user_specs[0]) updated_user_spec["password"] = '******' rows = import_users_and_groups( self.domain.name, list([updated_user_spec]), [], )['messages']['rows'] self.assertEqual( rows[0]['flag'], 'Password is not strong enough. Try making your password more complex.' )
class TestCreditStripePaymentHandler(TransactionTestCase): def setUp(self): super(TestCreditStripePaymentHandler, self).setUp() generator.instantiate_accounting() self.domain = Domain(name='test-domain') self.domain.save() self.payment_method = PaymentMethod() self.payment_method.save() self.account, _ = BillingAccount.get_or_create_account_by_domain( self.domain.name, created_by='*****@*****.**') def tearDown(self): self.domain.delete() PaymentRecord.objects.all().delete() self.payment_method.delete() self.account.delete() super(TestCreditStripePaymentHandler, self).tearDown() @patch.object(stripe.Charge, 'create') def test_working_process_request(self, mock_create): self._call_process_request() self.assertEqual(PaymentRecord.objects.count(), 1) self.assertEqual(mock_create.call_count, 1) @patch.object(stripe.Charge, 'create') def test_when_stripe_errors_no_payment_record_exists(self, mock_create): mock_create.side_effect = Exception self._call_process_request() self.assertEqual(PaymentRecord.objects.count(), 0) @patch.object(stripe.Charge, 'create') @patch.object(PaymentRecord, 'create_record') def test_when_create_record_fails_stripe_is_not_charged( self, mock_create_record, mock_create): mock_create_record.side_effect = Exception try: self._call_process_request() except: pass self.assertEqual(PaymentRecord.objects.count(), 0) self.assertEqual(mock_create.call_count, 0) def _call_process_request(self): CreditStripePaymentHandler(self.payment_method, self.domain, self.account, post_data={}).process_request( RequestFactory().post( '', {'amount': 1}))
class TestDeleteDomain(TestCase): def _create_data(self, domain_name): product = Product(domain=domain_name, name='test-product') product.save() location = Location( domain=domain_name, site_code='testcode', name='test1', location_type='facility' ) location.save() self.locations[domain_name] = location.sql_location user = CommCareUser.create( domain=domain_name, username='******'.format(domain_name), password='******' ) FacilityInCharge.objects.create( user_id=user.get_id, location=location.sql_location ) def setUp(self): self.domain = Domain(name="test", is_active=True) self.domain.save() self.domain2 = Domain(name="test2", is_active=True) self.domain2.save() self.locations = {} LocationType.objects.create( domain='test', name='facility', ) LocationType.objects.create( domain='test2', name='facility', ) self._create_data('test') self._create_data('test2') def test_pre_delete_signal_receiver(self): self.domain.delete() self.assertEqual(FacilityInCharge.objects.filter(location=self.locations['test']).count(), 0) self.assertEqual(FacilityInCharge.objects.filter(location=self.locations['test2']).count(), 1) def tearDown(self): FacilityInCharge.objects.all().delete() self.domain2.delete()
class TestUserBulkUploadStrongPassword(TestCase, DomainSubscriptionMixin): def setUp(self): super(TestUserBulkUploadStrongPassword, self).setUp() delete_all_users() self.domain_name = 'mydomain' self.domain = Domain(name=self.domain_name) self.domain.strong_mobile_passwords = True self.domain.save() self.user_specs = [{ 'username': '******', 'user_id': '1989', 'name': 'Taylor Swift', 'language': None, 'is_active': 'True', 'phone-number': '8675309', 'password': '******', 'email': None }] def tearDown(self): self.domain.delete() super(TestUserBulkUploadStrongPassword, self).tearDown() def test_duplicate_password(self): user_spec = [{ 'username': '******', 'user_id': '1990', 'name': 'Tom Hiddleston', 'language': None, 'is_active': 'True', 'phone-number': '8675309', 'password': '******', 'email': None }] rows = bulk_upload_async( self.domain.name, list(user_spec + self.user_specs), list([]), )['messages']['rows'] self.assertEqual(rows[0]['flag'], 'Provide a unique password for each mobile worker') def test_weak_password(self): updated_user_spec = deepcopy(self.user_specs[0]) updated_user_spec["password"] = '******' rows = bulk_upload_async( self.domain.name, list([updated_user_spec]), list([]), )['messages']['rows'] self.assertEqual(rows[0]['flag'], 'Please provide a stronger password')
class TestCreditStripePaymentHandler(TransactionTestCase): def setUp(self): super(TestCreditStripePaymentHandler, self).setUp() self.domain = Domain(name='test-domain') self.domain.save() self.payment_method = PaymentMethod() self.payment_method.save() self.account, _ = BillingAccount.get_or_create_account_by_domain( self.domain.name, created_by='*****@*****.**' ) def tearDown(self): self.domain.delete() PaymentRecord.objects.all().delete() self.payment_method.delete() self.account.delete() super(TestCreditStripePaymentHandler, self).tearDown() @patch.object(stripe.Charge, 'create') def test_working_process_request(self, mock_create): self._call_process_request() self.assertEqual(PaymentRecord.objects.count(), 1) self.assertEqual(mock_create.call_count, 1) @patch.object(stripe.Charge, 'create') def test_when_stripe_errors_no_payment_record_exists(self, mock_create): mock_create.side_effect = Exception self._call_process_request() self.assertEqual(PaymentRecord.objects.count(), 0) @patch.object(stripe.Charge, 'create') @patch.object(PaymentRecord, 'create_record') def test_when_create_record_fails_stripe_is_not_charged(self, mock_create_record, mock_create): mock_create_record.side_effect = Exception try: self._call_process_request() except: pass self.assertEqual(PaymentRecord.objects.count(), 0) self.assertEqual(mock_create.call_count, 0) def _call_process_request(self): CreditStripePaymentHandler( self.payment_method, self.domain, self.account, post_data={} ).process_request( RequestFactory().post('', {'amount': 1}) )
class TestDeleteDomain(TestCase): def _create_data(self, domain_name): product = Product(domain=domain_name, name='test-product') product.save() location = make_location( domain=domain_name, site_code='testcode', name='test1', location_type='facility' ) location.save() self.locations[domain_name] = location.sql_location user = CommCareUser.create( domain=domain_name, username='******'.format(domain_name), password='******' ) FacilityInCharge.objects.create( user_id=user.get_id, location=location.sql_location ) def setUp(self): self.domain = Domain(name="test", is_active=True) self.domain.save() self.domain2 = Domain(name="test2", is_active=True) self.domain2.save() self.locations = {} LocationType.objects.create( domain='test', name='facility', ) LocationType.objects.create( domain='test2', name='facility', ) self._create_data('test') self._create_data('test2') def test_pre_delete_signal_receiver(self): self.domain.delete() self.assertEqual(FacilityInCharge.objects.filter(location=self.locations['test']).count(), 0) self.assertEqual(FacilityInCharge.objects.filter(location=self.locations['test2']).count(), 1) def tearDown(self): FacilityInCharge.objects.all().delete() self.domain2.delete()
class DomainCalculatedPropertiesTest(TestCase): @classmethod def setUpClass(cls): super(DomainCalculatedPropertiesTest, cls).setUpClass() cls.es = [{ 'info': i, 'instance': get_es_new(), } for i in [ CASE_INDEX_INFO, SMS_INDEX_INFO, XFORM_INDEX_INFO, USER_INDEX_INFO ]] def setUp(self): self.domain = Domain(name='test-b9289e19d819') self.domain.save() for es in self.es: ensure_index_deleted(es['info'].index) initialize_index_and_mapping(es['instance'], es['info']) self._set_up_sms_es() def _set_up_sms_es(self): sms_doc = { '_id': 'some_sms_id', 'domain': self.domain.name, 'direction': INCOMING, 'date': json_format_datetime(datetime.datetime.utcnow()), 'doc_type': SMS_INDEX_INFO.type, } send_to_elasticsearch( index=SMS_INDEX_INFO.index, doc_type=SMS_INDEX_INFO.type, doc_id=sms_doc['_id'], es_getter=get_es_new, name='ElasticProcessor', data=sms_doc, update=False, ) refresh_elasticsearch_index('sms') def tearDown(self): self.domain.delete() def test_sanity(self): all_stats = all_domain_stats() props = calced_props(self.domain, self.domain._id, all_stats) self.assertFalse(props['cp_has_app']) # ensure serializable json.dumps(props) def test_sms(self): self.assertEqual(SMSES().count(), 1) self.assertEqual(sms(self.domain.name, INCOMING), 1) self.assertEqual(sms(self.domain.name, OUTGOING), 0)
class BETSBeneficiaryRepeaterTest(ENikshayRepeaterTestBase): def setUp(self): super(BETSBeneficiaryRepeaterTest, self).setUp() self.domain_obj = Domain(name=self.domain) self.domain_obj.save() self.repeater = BETSBeneficiaryRepeater( domain=self.domain, url='super-cool-url', ) self.repeater.save() loc_type = LocationType.objects.create( domain=self.domain, name="loc_type", administrative=True, ) self.real_location = SQLLocation.objects.create( domain=self.domain, name="real_location", site_code="real_location", location_type=loc_type, metadata={ 'is_test': 'no', 'nikshay_code': 'nikshay_code' }, ) self.test_location = SQLLocation.objects.create( domain=self.domain, name="test_location", site_code="test_location", location_type=loc_type, metadata={ 'is_test': 'yes', 'nikshay_code': 'nikshay_code' }, ) def tearDown(self): super(BETSBeneficiaryRepeaterTest, self).tearDown() self.domain_obj.delete() def create_person_case(self, location_id, private=True): case = get_person_case_structure(None, self.episode_id) case.attrs['owner_id'] = location_id case.attrs['update']['current_episode_type'] = 'confirmed_tb' case.attrs['update']['contact_phone_number'] = '911234567890' case.attrs['update'][ ENROLLED_IN_PRIVATE] = "true" if private else "false" return self.factory.create_or_update_cases([case])[0]
class RegistrationTestCase(BaseSMSTest): def setUp(self): super(RegistrationTestCase, self).setUp() self.domain = 'sms-reg-test-domain' self.domain_obj = Domain(name=self.domain) self.domain_obj.save() self.create_account_and_subscription(self.domain) self.domain_obj = Domain.get(self.domain_obj.get_id) self.backend = SQLTestSMSBackend.objects.create( name='BACKEND', is_global=False, domain=self.domain, hq_api_id=SQLTestSMSBackend.get_api_id() ) SQLMobileBackendMapping.set_default_domain_backend(self.domain, self.backend) def tearDown(self): delete_domain_phone_numbers(self.domain) SQLMobileBackendMapping.unset_default_domain_backend(self.domain) self.backend.delete() self.domain_obj.delete() super(RegistrationTestCase, self).tearDown() def test_sms_registration(self): formatted_username = format_username('tester', self.domain) # Test without mobile worker registration enabled incoming('+9991234567', 'JOIN {} WORKER tester'.format(self.domain), self.backend.hq_api_id) self.assertIsNone(CommCareUser.get_by_username(formatted_username)) # Test with mobile worker registration enabled self.domain_obj.sms_mobile_worker_registration_enabled = True self.domain_obj.save() incoming('+9991234567', 'JOIN {} WORKER tester'.format(self.domain), self.backend.hq_api_id) self.assertIsNotNone(CommCareUser.get_by_username(formatted_username)) # Test a duplicate registration prev_num_users = num_mobile_users(self.domain) incoming('+9991234568', 'JOIN {} WORKER tester'.format(self.domain), self.backend.hq_api_id) current_num_users = num_mobile_users(self.domain) self.assertEqual(prev_num_users, current_num_users)
class IncomingPostTest(TestCase): INDIA_TZ_OFFSET = timedelta(hours=5.5) def setUp(self): self.domain = Domain(name='mockdomain') self.domain.save() SMS.by_domain(self.domain.name).delete() self.user = '******' self.password = '******' self.number = 5555551234 self.couch_user = WebUser.create(self.domain.name, self.user, self.password) self.couch_user.add_phone_number(self.number) self.couch_user.save() self.message_ascii = 'It Works' self.message_utf_hex = '0939093F0928094D092609400020091509300924093E00200939094800200907093800200938092E092F00200915093E092E002009390948003F' def tearDown(self): self.couch_user.delete() self.domain.delete() def testPostToIncomingAscii(self): fake_post = { InboundParams.SENDER: str(self.number), InboundParams.MESSAGE: self.message_ascii, InboundParams.MID: '00001', InboundParams.DCS: '0' } response, log = post(fake_post) self.assertEqual(200, response.status_code) self.assertEqual(self.message_ascii, log.text) self.assertEqual(INCOMING, log.direction) self.assertEqual(log.backend_message_id, fake_post[InboundParams.MID]) def testPostToIncomingUtf(self): fake_post = { InboundParams.SENDER: str(self.number), InboundParams.MESSAGE: self.message_utf_hex, InboundParams.MID: '00002', InboundParams.DCS: '8' } response, log = post(fake_post) self.assertEqual(200, response.status_code) self.assertEqual( self.message_utf_hex.decode("hex").decode("utf_16_be"), log.text) self.assertEqual(INCOMING, log.direction) self.assertEqual(log.backend_message_id, fake_post[InboundParams.MID])
class BaseReminderTestCase(BaseAccountingTest, DomainSubscriptionMixin): def setUp(self): super(BaseReminderTestCase, self).setUp() self.domain_obj = Domain(name="test") self.domain_obj.save() # Prevent resource conflict self.domain_obj = Domain.get(self.domain_obj._id) self.setup_subscription(self.domain_obj.name, SoftwarePlanEdition.ADVANCED) self.sms_backend, self.sms_backend_mapping = setup_default_sms_test_backend() def tearDown(self): delete_domain_phone_numbers('test') self.sms_backend_mapping.delete() self.sms_backend.delete() self.teardown_subscription() self.domain_obj.delete()
class TestDeleteDomain(TestCase): def setUp(self): self.domain = Domain(name="test", is_active=True) self.domain.save() self.domain2 = Domain(name="test2", is_active=True) self.domain2.save() StockDataCheckpoint.objects.create( domain='test', api='test', limit=100, offset=0 ) StockDataCheckpoint.objects.create( domain='test2', api='test', limit=100, offset=0 ) MigrationCheckpoint.objects.create( domain='test', api='test', limit=100, offset=0 ) MigrationCheckpoint.objects.create( domain='test2', api='test', limit=100, offset=0 ) def test_pre_delete_signal_receiver(self): self.domain.delete() self.assertEqual(MigrationCheckpoint.objects.filter(domain='test').count(), 0) self.assertEqual(StockDataCheckpoint.objects.filter(domain='test').count(), 0) self.assertEqual(MigrationCheckpoint.objects.filter(domain='test2').count(), 1) self.assertEqual(StockDataCheckpoint.objects.filter(domain='test2').count(), 1) def tearDown(self): self.domain2.delete()
class BaseReminderTestCase(TestCase): def setUp(self): self.domain_obj = Domain(name="test") self.domain_obj.save() # Prevent resource conflict self.domain_obj = Domain.get(self.domain_obj._id) self.sms_backend = TestSMSBackend(named="MOBILE_BACKEND_TEST", is_global=True) self.sms_backend.save() self.sms_backend_mapping = BackendMapping(is_global=True,prefix="*",backend_id=self.sms_backend._id) self.sms_backend_mapping.save() def tearDown(self): self.sms_backend_mapping.delete() self.sms_backend.delete() self.domain_obj.delete()
class ENikshayLocationStructureMixin(object): def setUp(self): self.domain = getattr(self, 'domain', 'fake-domain-from-mixin') self.project = Domain(name=self.domain) self.project.save() _, locations = setup_enikshay_locations(self.domain) self.sto = locations['STO'] self.sto.metadata = { 'nikshay_code': 'MH', } self.sto.save() self.dto = locations['DTO'] self.dto.metadata = { 'nikshay_code': 'ABD', } self.dto.save() self.drtb_hiv = locations['DRTB-HIV'] self.drtb_hiv.save() self.tu = locations['TU'] self.tu.metadata = { 'nikshay_code': '1', } self.tu.save() self.phi = locations['PHI'] self.phi.metadata = { 'nikshay_code': '2', 'is_test': 'no', } self.phi.save() super(ENikshayLocationStructureMixin, self).setUp() def tearDown(self): self.project.delete() SQLLocation.objects.all().delete() LocationType.objects.all().delete() super(ENikshayLocationStructureMixin, self).tearDown() def assign_person_to_location(self, location_id): return self.create_case( CaseStructure(case_id=self.person_id, attrs={"update": dict(owner_id=location_id, )}))[0]
class OptTestCase(TestCase): def setUp(self): self.domain = "opt-test" self.domain_obj = Domain(name=self.domain) self.domain_obj.save() self.backend = TestSMSBackend(is_global=True) self.backend.save() self.backend_mapping = BackendMapping( is_global=True, prefix="*", backend_id=self.backend._id, ) self.backend_mapping.save() def test_opt_out_and_opt_in(self): self.assertEqual(PhoneNumber.objects.count(), 0) incoming("99912345678", "stop", "GVI") self.assertEqual(PhoneNumber.objects.count(), 1) phone_number = PhoneNumber.objects.get(phone_number="99912345678") self.assertFalse(phone_number.send_sms) incoming("99912345678", "start", "GVI") self.assertEqual(PhoneNumber.objects.count(), 1) phone_number = PhoneNumber.objects.get(phone_number="99912345678") self.assertTrue(phone_number.send_sms) def test_sending_to_opted_out_number(self): self.assertEqual(PhoneNumber.objects.count(), 0) self.assertTrue(send_sms(self.domain, None, "999123456789", "hello")) incoming("999123456789", "stop", "GVI") self.assertEqual(PhoneNumber.objects.count(), 1) phone_number = PhoneNumber.objects.get(phone_number="999123456789") self.assertFalse(phone_number.send_sms) self.assertFalse(send_sms(self.domain, None, "999123456789", "hello")) def tearDown(self): self.backend_mapping.delete() self.backend.delete() self.domain_obj.delete()
class DeviceIdUpdateTest(ENikshayCaseStructureMixin, TestCase): def setUp(self): super(DeviceIdUpdateTest, self).setUp() self.domain_obj = Domain(name=self.domain) self.domain_obj.save() self.web_user_username = "******" self.web_user_password = "******" self.web_user = WebUser.create( self.domain, username=self.web_user_username, password=self.web_user_password, ) def tearDown(self): self.domain_obj.delete() super(DeviceIdUpdateTest, self).tearDown() def test_login_as(self): self.web_user.is_superuser = True self.web_user.save() restore_uri = reverse('ota_restore', args=[self.domain]) auth_header = _get_auth_header(self.web_user_username, self.web_user_password) client = Client(HTTP_AUTHORIZATION=auth_header) device_id = "foo" # get the seq id before the change is published kafka_seq = get_topic_offset(topics.SYNCLOG_SQL) resp = client.get(restore_uri, data={ 'as': self.username, "device_id": device_id }, follow=True) self.assertEqual(resp.status_code, 200) pillow = get_user_sync_history_pillow() pillow.process_changes(since=kafka_seq, forever=False) restored_as_user = CommCareUser.get_by_username(self.username) self.assertEqual(len(restored_as_user.devices), 1) self.assertEqual(restored_as_user.devices[0].device_id, device_id)
class IncomingPostTest(TestCase): INDIA_TZ_OFFSET = timedelta(hours=5.5) def setUp(self): self.domain = Domain(name='mockdomain') self.domain.save() all_logs = SMSLog.by_domain_asc(self.domain.name).all() for log in all_logs: log.delete() self.user = '******' self.password = '******' self.number = 5555551234 self.couch_user = WebUser.create(self.domain.name, self.user, self.password) self.couch_user.add_phone_number(self.number) self.couch_user.save() self.message_ascii = 'It Works' self.message_utf_hex = '0939093F0928094D092609400020091509300924093E00200939094800200907093800200938092E092F00200915093E092E002009390948003F' def tearDown(self): self.couch_user.delete() self.domain.delete() def testPostToIncomingAscii(self): fake_post = {InboundParams.SENDER: str(self.number), InboundParams.MESSAGE: self.message_ascii, InboundParams.MID: '00001', InboundParams.DCS: '0'} response, log = post(fake_post) self.assertEqual(200, response.status_code) self.assertEqual(self.message_ascii, log.text) self.assertEqual(INCOMING, log.direction) self.assertEqual(log.backend_message_id, fake_post[InboundParams.MID]) def testPostToIncomingUtf(self): fake_post = {InboundParams.SENDER: str(self.number), InboundParams.MESSAGE: self.message_utf_hex, InboundParams.MID: '00002', InboundParams.DCS: '8'} response, log = post(fake_post) self.assertEqual(200, response.status_code) self.assertEqual(self.message_utf_hex.decode("hex").decode("utf_16_be"), log.text) self.assertEqual(INCOMING, log.direction) self.assertEqual(log.backend_message_id, fake_post[InboundParams.MID])
def test_deleted_domain_exists(self): x = Domain(name='x') x.save() y = Domain(name='y') y.save() y.delete(leave_tombstone=True) self.addCleanup(x.delete) self.addCleanup(y.delete) self.assertTrue(domain_exists('x')) self.assertFalse(deleted_domain_exists('x')) self.assertTrue(domain_or_deleted_domain_exists('x')) self.assertFalse(domain_exists('y')) self.assertTrue(deleted_domain_exists('y')) self.assertTrue(domain_or_deleted_domain_exists('y')) self.assertTrue(len(list(iter_all_domains_and_deleted_domains_with_name('x'))), 1) self.assertTrue(len(list(iter_all_domains_and_deleted_domains_with_name('y'))), 1)
class TestCustomerBillingRecord(BaseAccountingTest): def setUp(self): super(TestCustomerBillingRecord, self).setUp() self.billing_contact = generator.create_arbitrary_web_user_name() self.dimagi_user = generator.create_arbitrary_web_user_name( is_dimagi=True) self.domain = Domain(name='test') self.domain.save() self.invoice_start, self.invoice_end = get_previous_month_date_range() self.currency = generator.init_default_currency() self.account = generator.billing_account(self.dimagi_user, self.billing_contact) self.account.is_customer_billing_account = True self.account.save() self.subscription_length = 4 # months subscription_start_date = datetime.date(2016, 2, 23) subscription_end_date = add_months_to_date(subscription_start_date, self.subscription_length) self.subscription = generator.generate_domain_subscription( self.account, self.domain, date_start=subscription_start_date, date_end=subscription_end_date, ) self.invoice = CustomerInvoice(account=self.account, date_start=self.invoice_start, date_end=self.invoice_end, is_hidden=False) self.customer_billing_record = CustomerBillingRecord( invoice=self.invoice) def tearDown(self): self.domain.delete() super(TestCustomerBillingRecord, self).tearDown() def test_should_send_email(self): self.assertTrue(self.customer_billing_record.should_send_email) def test_should_send_email_hidden(self): self.assertTrue(self.customer_billing_record.should_send_email) self.invoice.is_hidden = True self.assertFalse(self.customer_billing_record.should_send_email)
class OptTestCase(BaseAccountingTest, DomainSubscriptionMixin): def setUp(self): super(OptTestCase, self).setUp() self.domain = "opt-test" self.domain_obj = Domain(name=self.domain) self.domain_obj.save() self.setup_subscription(self.domain_obj.name, SoftwarePlanEdition.ADVANCED) self.backend, self.backend_mapping = setup_default_sms_test_backend() def test_opt_out_and_opt_in(self): self.assertEqual(PhoneBlacklist.objects.count(), 0) incoming("99912345678", "stop", "GVI") self.assertEqual(PhoneBlacklist.objects.count(), 1) phone_number = PhoneBlacklist.objects.get(phone_number="99912345678") self.assertFalse(phone_number.send_sms) incoming("99912345678", "start", "GVI") self.assertEqual(PhoneBlacklist.objects.count(), 1) phone_number = PhoneBlacklist.objects.get(phone_number="99912345678") self.assertTrue(phone_number.send_sms) def test_sending_to_opted_out_number(self): self.assertEqual(PhoneBlacklist.objects.count(), 0) self.assertTrue(send_sms(self.domain, None, "999123456789", "hello")) incoming("999123456789", "stop", "GVI") self.assertEqual(PhoneBlacklist.objects.count(), 1) phone_number = PhoneBlacklist.objects.get(phone_number="999123456789") self.assertFalse(phone_number.send_sms) self.assertFalse(send_sms(self.domain, None, "999123456789", "hello")) def tearDown(self): delete_domain_phone_numbers(self.domain) self.backend_mapping.delete() self.backend.delete() self.domain_obj.delete() self.teardown_subscription()
class TestCustomerBillingRecord(BaseAccountingTest): def setUp(self): super(TestCustomerBillingRecord, self).setUp() self.billing_contact = generator.create_arbitrary_web_user_name() self.dimagi_user = generator.create_arbitrary_web_user_name(is_dimagi=True) self.domain = Domain(name='test') self.domain.save() self.invoice_start, self.invoice_end = get_previous_month_date_range() self.currency = generator.init_default_currency() self.account = generator.billing_account(self.dimagi_user, self.billing_contact) self.account.is_customer_billing_account = True self.account.save() self.subscription_length = 4 # months subscription_start_date = datetime.date(2016, 2, 23) subscription_end_date = add_months_to_date(subscription_start_date, self.subscription_length) self.subscription = generator.generate_domain_subscription( self.account, self.domain, date_start=subscription_start_date, date_end=subscription_end_date, ) self.invoice = CustomerInvoice( account=self.account, date_start=self.invoice_start, date_end=self.invoice_end, is_hidden=False ) self.customer_billing_record = CustomerBillingRecord(invoice=self.invoice) def tearDown(self): self.domain.delete() super(TestCustomerBillingRecord, self).tearDown() def test_should_send_email(self): self.assertTrue(self.customer_billing_record.should_send_email) def test_should_send_email_hidden(self): self.assertTrue(self.customer_billing_record.should_send_email) self.invoice.is_hidden = True self.assertFalse(self.customer_billing_record.should_send_email)
class TestDomainViews(TestCase): def setUp(self): self.client = Client() self.domain = Domain(name="fandago", is_active=True) self.domain.save() self.username = '******' self.password = '******' self.user = WebUser.create(self.domain.name, self.username, self.password) self.user.set_role(self.domain.name, 'admin') self.user.save() def tearDown(self): self.user.delete() self.domain.delete() def test_add_repeater(self): forwarding_url = 'https://example.com/forwarding' self.client.login(username=self.username, password=self.password) post_url = reverse('add_repeater', kwargs={ 'domain': self.domain.name, 'repeater_type': 'AppStructureRepeater' }) response = self.client.post(post_url, {'url': forwarding_url}, follow=True) self.assertEqual(response.status_code, 200) self.client.logout() app_structure_repeaters = AppStructureRepeater.by_domain( self.domain.name) self.assertEqual(len(app_structure_repeaters), 1) for app_structure_repeater in app_structure_repeaters: app_structure_repeater.delete()
class TestCaseListFilter(TestCase): def setUp(self): self.subject = CaseListFilter clear_domain_names('test') self.domain = Domain(name='test', is_active=True) self.domain.save() self.location_type = LocationType.objects.create( domain=self.domain.name, name='testtype') self.user_assigned_locations = [ make_loc('root', domain=self.domain.name, type=self.location_type.code).sql_location ] self.request = RequestFactory() self.request.couch_user = WebUser() self.request.domain = self.domain def tearDown(self): self.domain.delete() super().tearDown() @patch('corehq.apps.users.models.WebUser.get_sql_locations') def test_default_selections_for_full_access(self, assigned_locations_patch): self.request.can_access_all_locations = True self.request.project = self.domain emwf = self.subject(self.request) default_selections = emwf.get_default_selections() self.assertEqual(default_selections, emwf.default_selections) assert not assigned_locations_patch.called @patch('corehq.apps.users.models.WebUser.get_sql_locations') def test_default_selections_for_restricted_access( self, assigned_locations_patch): self.request.can_access_all_locations = False self.request.project = self.domain emwf = self.subject(self.request) emwf.get_default_selections() assert assigned_locations_patch.called
class TestSoftwarePlanChanges(BaseAccountingTest): def setUp(self): super(TestSoftwarePlanChanges, self).setUp() self.domain = Domain( name="test-plan-changes", is_active=True, ) self.domain.save() self.domain2 = Domain( name="other-domain", is_active=True, ) self.domain2.save() self.admin_username = generator.create_arbitrary_web_user_name() self.account = BillingAccount.get_or_create_account_by_domain( self.domain.name, created_by=self.admin_username)[0] self.advanced_plan = DefaultProductPlan.get_default_plan_version( edition=SoftwarePlanEdition.ADVANCED) self.advanced_plan.plan.max_domains = 1 self.community_plan = DefaultProductPlan.get_default_plan_version( edition=SoftwarePlanEdition.COMMUNITY) def tearDown(self): self.domain.delete() self.domain2.delete() super(TestSoftwarePlanChanges, self).tearDown() def test_change_plan_blocks_on_max_domains(self): Subscription.new_domain_subscription(self.account, self.domain.name, self.advanced_plan) sub2 = Subscription.new_domain_subscription(self.account, self.domain2.name, self.community_plan) self.assertRaises(SubscriptionAdjustmentError, lambda: sub2.change_plan(self.advanced_plan))
class TestSoftwarePlanChanges(BaseAccountingTest): def setUp(self): super(TestSoftwarePlanChanges, self).setUp() self.domain = Domain( name="test-plan-changes", is_active=True, ) self.domain.save() self.domain2 = Domain( name="other-domain", is_active=True, ) self.domain2.save() self.admin_username = generator.create_arbitrary_web_user_name() self.account = BillingAccount.get_or_create_account_by_domain( self.domain.name, created_by=self.admin_username)[0] self.advanced_plan = DefaultProductPlan.get_default_plan_version(edition=SoftwarePlanEdition.ADVANCED) self.advanced_plan.plan.max_domains = 1 self.community_plan = DefaultProductPlan.get_default_plan_version(edition=SoftwarePlanEdition.COMMUNITY) def tearDown(self): self.domain.delete() self.domain2.delete() super(TestSoftwarePlanChanges, self).tearDown() def test_change_plan_blocks_on_max_domains(self): Subscription.new_domain_subscription( self.account, self.domain.name, self.advanced_plan ) sub2 = Subscription.new_domain_subscription( self.account, self.domain2.name, self.community_plan ) self.assertRaises(SubscriptionAdjustmentError, lambda: sub2.change_plan(self.advanced_plan))
class TestSubscriptionForm(BaseAccountingTest): def setUp(self): super(TestSubscriptionForm, self).setUp() self.domain = Domain( name="test-sub-form", is_active=True ) self.domain.save() self.domain2 = Domain( name="test-sub-form-2", is_active=True ) self.domain2.save() self.web_user = WebUser.create( self.domain.name, generator.create_arbitrary_web_user_name(), 'testpwd' ) self.account = BillingAccount.get_or_create_account_by_domain( self.domain.name, created_by=self.web_user.username )[0] self.account.save() self.customer_account = BillingAccount.get_or_create_account_by_domain( self.domain2.name, created_by=self.web_user.username )[0] self.customer_account.is_customer_billing_account = True self.customer_account.save() self.plan = DefaultProductPlan.get_default_plan_version(edition=SoftwarePlanEdition.ADVANCED) self.customer_plan = DefaultProductPlan.get_default_plan_version(edition=SoftwarePlanEdition.ADVANCED) self.customer_plan.plan.is_customer_software_plan = True def tearDown(self): self.domain.delete() self.domain2.delete() super(TestSubscriptionForm, self).tearDown() def test_regular_plan_not_added_to_customer_account(self): subscription = Subscription.new_domain_subscription( domain=self.domain.name, plan_version=self.plan, account=self.account ) subscription_form = SubscriptionForm( subscription=subscription, account_id=self.account.id, web_user=self.web_user, ) subscription_form.cleaned_data = { 'active_accounts': self.customer_account.id, 'start_date': datetime.date.today(), 'end_date': None, 'do_not_invoice': None, 'no_invoice_reason': None, 'do_not_email_invoice': None, 'do_not_email_reminder': None, 'auto_generate_credits': None, 'skip_invoicing_if_no_feature_charges': None, 'salesforce_contract_id': None, 'service_type': None, 'pro_bono_status': None, 'funding_source': None, 'skip_auto_downgrade': None, 'skip_auto_downgrade_reason': None } self.assertRaises(ValidationError, lambda: subscription_form.clean_active_accounts()) def test_customer_plan_not_added_to_regular_account(self): subscription = Subscription.new_domain_subscription( domain=self.domain.name, plan_version=self.customer_plan, account=self.customer_account ) subscription_form = SubscriptionForm( subscription=subscription, account_id=self.customer_plan.id, web_user=self.web_user, ) subscription_form.cleaned_data = { 'active_accounts': self.account.id, 'start_date': datetime.date.today(), 'end_date': None, 'do_not_invoice': None, 'no_invoice_reason': None, 'do_not_email_invoice': None, 'do_not_email_reminder': None, 'auto_generate_credits': None, 'skip_invoicing_if_no_feature_charges': None, 'salesforce_contract_id': None, 'service_type': None, 'pro_bono_status': None, 'funding_source': None, 'skip_auto_downgrade': None, 'skip_auto_downgrade_reason': None } self.assertRaises(ValidationError, lambda: subscription_form.clean_active_accounts())
class TestHardDeleteSQLFormsAndCases(TestCase): def setUp(self): super(TestHardDeleteSQLFormsAndCases, self).setUp() self.domain = Domain(name='test') self.domain.save() self.domain2 = Domain(name='test2') self.domain2.save() def tearDown(self): self.domain2.delete() super(TestHardDeleteSQLFormsAndCases, self).tearDown() @override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True) def test_hard_delete_forms(self): for domain_name in [self.domain.name, self.domain2.name]: create_form_for_test(domain_name) self.assertEqual(len(FormAccessors(domain_name).get_all_form_ids_in_domain()), 1) self.domain.delete() self.assertEqual(len(FormAccessors(self.domain.name).get_all_form_ids_in_domain()), 0) self.assertEqual(len(FormAccessors(self.domain2.name).get_all_form_ids_in_domain()), 1) self.assertEqual(len(FormAccessorSQL.get_deleted_form_ids_in_domain(self.domain.name)), 1) self.assertEqual(len(FormAccessorSQL.get_deleted_form_ids_in_domain(self.domain2.name)), 0) call_command('hard_delete_forms_and_cases_in_domain', self.domain.name, noinput=True) self.assertEqual(len(FormAccessors(self.domain.name).get_all_form_ids_in_domain()), 0) self.assertEqual(len(FormAccessors(self.domain2.name).get_all_form_ids_in_domain()), 1) self.assertEqual(len(FormAccessorSQL.get_deleted_form_ids_in_domain(self.domain.name)), 0) self.assertEqual(len(FormAccessorSQL.get_deleted_form_ids_in_domain(self.domain2.name)), 0) @override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True) def test_hard_delete_forms_none_to_delete(self): for domain_name in [self.domain.name, self.domain2.name]: create_form_for_test(domain_name) self.assertEqual(len(FormAccessors(domain_name).get_all_form_ids_in_domain()), 1) self.domain.delete() self.assertEqual(len(FormAccessors(self.domain.name).get_all_form_ids_in_domain()), 0) self.assertEqual(len(FormAccessors(self.domain2.name).get_all_form_ids_in_domain()), 1) self.assertEqual(len(FormAccessorSQL.get_deleted_form_ids_in_domain(self.domain.name)), 1) self.assertEqual(len(FormAccessorSQL.get_deleted_form_ids_in_domain(self.domain2.name)), 0) call_command('hard_delete_forms_and_cases_in_domain', self.domain2.name, noinput=True) self.assertEqual(len(FormAccessors(self.domain.name).get_all_form_ids_in_domain()), 0) self.assertEqual(len(FormAccessors(self.domain2.name).get_all_form_ids_in_domain()), 1) self.assertEqual(len(FormAccessorSQL.get_deleted_form_ids_in_domain(self.domain.name)), 1) self.assertEqual(len(FormAccessorSQL.get_deleted_form_ids_in_domain(self.domain2.name)), 0) @override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True) def test_hard_delete_cases(self): for domain_name in [self.domain.name, self.domain2.name]: CaseFactory(domain_name).create_case() self.assertEqual(len(CaseAccessors(domain_name).get_case_ids_in_domain()), 1) self.domain.delete() self.assertEqual(len(CaseAccessors(self.domain.name).get_case_ids_in_domain()), 0) self.assertEqual(len(CaseAccessors(self.domain2.name).get_case_ids_in_domain()), 1) self.assertEqual(len(CaseAccessorSQL.get_deleted_case_ids_in_domain(self.domain.name)), 1) self.assertEqual(len(CaseAccessorSQL.get_deleted_case_ids_in_domain(self.domain2.name)), 0) call_command('hard_delete_forms_and_cases_in_domain', self.domain.name, noinput=True) self.assertEqual(len(CaseAccessors(self.domain.name).get_case_ids_in_domain()), 0) self.assertEqual(len(CaseAccessors(self.domain2.name).get_case_ids_in_domain()), 1) self.assertEqual(len(CaseAccessorSQL.get_deleted_case_ids_in_domain(self.domain.name)), 0) self.assertEqual(len(CaseAccessorSQL.get_deleted_case_ids_in_domain(self.domain2.name)), 0) @override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True) def test_hard_delete_cases_none_to_delete(self): for domain_name in [self.domain.name, self.domain2.name]: CaseFactory(domain_name).create_case() self.assertEqual(len(CaseAccessors(domain_name).get_case_ids_in_domain()), 1) self.domain.delete() self.assertEqual(len(CaseAccessors(self.domain.name).get_case_ids_in_domain()), 0) self.assertEqual(len(CaseAccessors(self.domain2.name).get_case_ids_in_domain()), 1) self.assertEqual(len(CaseAccessorSQL.get_deleted_case_ids_in_domain(self.domain.name)), 1) self.assertEqual(len(CaseAccessorSQL.get_deleted_case_ids_in_domain(self.domain2.name)), 0) call_command('hard_delete_forms_and_cases_in_domain', self.domain2.name, noinput=True) self.assertEqual(len(CaseAccessors(self.domain.name).get_case_ids_in_domain()), 0) self.assertEqual(len(CaseAccessors(self.domain2.name).get_case_ids_in_domain()), 1) self.assertEqual(len(CaseAccessorSQL.get_deleted_case_ids_in_domain(self.domain.name)), 1) self.assertEqual(len(CaseAccessorSQL.get_deleted_case_ids_in_domain(self.domain2.name)), 0)
class BackendTestCase(BaseSMSTest): def get_or_create_site(self): site, created = Site.objects.get_or_create(id=settings.SITE_ID) if created: site.domain = 'localhost' site.name = 'localhost' site.save() return (site, created) def setUp(self): super(BackendTestCase, self).setUp() self.domain = "test-domain" self.domain2 = "test-domain2" self.site, self.site_created = self.get_or_create_site() self.domain_obj = Domain(name=self.domain) self.domain_obj.save() self.create_account_and_subscription(self.domain_obj.name) self.domain_obj = Domain.get(self.domain_obj._id) # Prevent resource conflict self.backend1 = TestCaseBackend(name="BACKEND1",is_global=True) self.backend1.save() self.backend2 = TestCaseBackend(name="BACKEND2",is_global=True) self.backend2.save() self.backend3 = TestCaseBackend(name="BACKEND3",is_global=True) self.backend3.save() self.backend4 = TestCaseBackend(name="BACKEND4",is_global=True) self.backend4.save() self.backend5 = TestCaseBackend(name="BACKEND5",domain=self.domain,is_global=False,authorized_domains=[]) self.backend5.save() self.backend6 = TestCaseBackend(name="BACKEND6",domain=self.domain2,is_global=False,authorized_domains=[self.domain]) self.backend6.save() self.backend7 = TestCaseBackend(name="BACKEND7",domain=self.domain2,is_global=False,authorized_domains=[]) self.backend7.save() self.backend8 = TestCaseBackend(name="BACKEND",domain=self.domain,is_global=False,authorized_domains=[]) self.backend8.save() self.backend9 = TestCaseBackend(name="BACKEND",domain=self.domain2,is_global=False,authorized_domains=[self.domain]) self.backend9.save() self.backend10 = TestCaseBackend(name="BACKEND",is_global=True) self.backend10.save() self.backend_mapping1 = BackendMapping(is_global=True,prefix="*",backend_id=self.backend1._id) self.backend_mapping1.save() self.backend_mapping2 = BackendMapping(is_global=True,prefix="1",backend_id=self.backend2._id) self.backend_mapping2.save() self.backend_mapping3 = BackendMapping(is_global=True,prefix="91",backend_id=self.backend3._id) self.backend_mapping3.save() self.backend_mapping4 = BackendMapping(is_global=True,prefix="265",backend_id=self.backend4._id) self.backend_mapping4.save() self.backend_mapping5 = BackendMapping(is_global=True, prefix="256", backend_id=self.backend5._id) self.backend_mapping5.save() self.backend_mapping6 = BackendMapping(is_global=True, prefix="25670", backend_id=self.backend6._id) self.backend_mapping6.save() self.backend_mapping7 = BackendMapping(is_global=True, prefix="25675", backend_id=self.backend7._id) self.backend_mapping7.save() self.case = CommCareCase(domain=self.domain) self.case.set_case_property("contact_phone_number","15551234567") self.case.set_case_property("contact_phone_number_is_verified", "1") self.case.save() self.contact = CommConnectCase.wrap(self.case.to_json()) settings.SMS_LOADED_BACKENDS.append("corehq.apps.sms.tests.TestCaseBackend") def tearDown(self): self.backend1.delete_invoke_doc() self.backend1.delete() self.backend_mapping1.delete() self.backend2.delete_invoke_doc() self.backend2.delete() self.backend_mapping2.delete() self.backend3.delete_invoke_doc() self.backend3.delete() self.backend_mapping3.delete() self.backend4.delete_invoke_doc() self.backend4.delete() self.backend_mapping4.delete() self.backend5.delete_invoke_doc() self.backend5.delete() self.backend_mapping5.delete() self.backend6.delete_invoke_doc() self.backend6.delete() self.backend_mapping6.delete() self.backend7.delete_invoke_doc() self.backend7.delete() self.backend_mapping7.delete() self.contact.delete_verified_number() self.case.delete() self.domain_obj.delete() if self.site_created: self.site.delete() settings.SMS_LOADED_BACKENDS.pop() super(BackendTestCase, self).tearDown() def test_multiple_country_prefixes(self): self.assertEqual(MobileBackend.auto_load('256800000000')._id, self.backend5._id) self.assertEqual(MobileBackend.auto_load('256700000000')._id, self.backend6._id) self.assertEqual(MobileBackend.auto_load('256750000000')._id, self.backend7._id) def test_backend(self): # Test the backend map self.assertTrue(send_sms(self.domain, None, "15551234567", "Test for BACKEND2")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertTrue(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertFalse(self.backend8.invoke_doc_exists()) self.assertFalse(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) self.backend2.delete_invoke_doc() self.assertFalse(self.backend2.invoke_doc_exists()) self.assertTrue(send_sms(self.domain, None, "9100000000", "Test for BACKEND3")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertTrue(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertFalse(self.backend8.invoke_doc_exists()) self.assertFalse(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) self.backend3.delete_invoke_doc() self.assertFalse(self.backend3.invoke_doc_exists()) self.assertTrue(send_sms(self.domain, None, "26500000000", "Test for BACKEND4")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertTrue(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertFalse(self.backend8.invoke_doc_exists()) self.assertFalse(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) self.backend4.delete_invoke_doc() self.assertFalse(self.backend4.invoke_doc_exists()) self.assertTrue(send_sms(self.domain, None, "25800000000", "Test for BACKEND1")) self.assertTrue(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertFalse(self.backend8.invoke_doc_exists()) self.assertFalse(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) self.backend1.delete_invoke_doc() self.assertFalse(self.backend1.invoke_doc_exists()) # Test overriding with a domain-level backend self.domain_obj = Domain.get(self.domain_obj._id) # Prevent resource conflict self.domain_obj.default_sms_backend_id = self.backend5._id self.domain_obj.save() self.assertTrue(send_sms(self.domain, None, "15551234567", "Test for BACKEND5")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertTrue(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertFalse(self.backend8.invoke_doc_exists()) self.assertFalse(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) self.backend5.delete_invoke_doc() self.assertFalse(self.backend5.invoke_doc_exists()) # Test use of backend that another domain owns but has granted access self.domain_obj.default_sms_backend_id = self.backend6._id self.domain_obj.save() self.assertTrue(send_sms(self.domain, None, "25800000000", "Test for BACKEND6")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertTrue(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertFalse(self.backend8.invoke_doc_exists()) self.assertFalse(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) self.backend6.delete_invoke_doc() self.assertFalse(self.backend6.invoke_doc_exists()) # Test backend access control self.domain_obj.default_sms_backend_id = self.backend7._id self.domain_obj.save() self.assertFalse(send_sms(self.domain, None, "25800000000", "Test for BACKEND7")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertFalse(self.backend8.invoke_doc_exists()) self.assertFalse(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) # Test sending to verified number with backend map self.domain_obj.default_sms_backend_id = None self.domain_obj.save() verified_number = self.contact.get_verified_number() self.assertTrue(verified_number is not None) self.assertTrue(verified_number.backend_id is None) self.assertEqual(verified_number.phone_number, "15551234567") self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND2")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertTrue(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertFalse(self.backend8.invoke_doc_exists()) self.assertFalse(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) self.backend2.delete_invoke_doc() self.assertFalse(self.backend2.invoke_doc_exists()) # Test sending to verified number with default domain backend self.domain_obj.default_sms_backend_id = self.backend5._id self.domain_obj.save() self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND5")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertTrue(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertFalse(self.backend8.invoke_doc_exists()) self.assertFalse(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) self.backend5.delete_invoke_doc() self.assertFalse(self.backend5.invoke_doc_exists()) # Test sending to verified number with a contact-level backend owned by the domain self.case.set_case_property("contact_backend_id", "BACKEND") self.case.save() self.contact = CommConnectCase.wrap(self.case.to_json()) verified_number = self.contact.get_verified_number() self.assertTrue(verified_number is not None) self.assertEqual(verified_number.backend_id, "BACKEND") self.assertEqual(verified_number.phone_number, "15551234567") self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertTrue(self.backend8.invoke_doc_exists()) self.assertFalse(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) self.backend8.delete_invoke_doc() self.assertFalse(self.backend8.invoke_doc_exists()) # Test sending to verified number with a contact-level backend granted to the domain by another domain self.backend8.delete() self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertTrue(self.backend9.invoke_doc_exists()) self.assertFalse(self.backend10.invoke_doc_exists()) self.backend9.delete_invoke_doc() self.assertFalse(self.backend9.invoke_doc_exists()) # Test sending to verified number with a contact-level global backend self.backend9.delete() self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertFalse(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.assertTrue(self.backend10.invoke_doc_exists()) self.backend10.delete_invoke_doc() self.assertFalse(self.backend10.invoke_doc_exists()) # Test raising exception if contact-level backend is not found self.backend10.delete() try: self.assertTrue(send_sms_to_verified_number(verified_number, "Test for BACKEND")) except BadSMSConfigException: pass else: self.assertTrue(False) # Test send_sms_with_backend self.assertTrue(send_sms_with_backend(self.domain, "+15551234567", "Test for BACKEND3", self.backend3._id)) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertTrue(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.backend3.delete_invoke_doc() self.assertFalse(self.backend3.invoke_doc_exists()) # Test send_sms_with_backend_name self.assertTrue(send_sms_with_backend_name(self.domain, "+15551234567", "Test for BACKEND3", "BACKEND3")) self.assertFalse(self.backend1.invoke_doc_exists()) self.assertFalse(self.backend2.invoke_doc_exists()) self.assertTrue(self.backend3.invoke_doc_exists()) self.assertFalse(self.backend4.invoke_doc_exists()) self.assertFalse(self.backend5.invoke_doc_exists()) self.assertFalse(self.backend6.invoke_doc_exists()) self.assertFalse(self.backend7.invoke_doc_exists()) self.backend3.delete_invoke_doc() self.assertFalse(self.backend3.invoke_doc_exists()) def test_sms_registration(self): formatted_username = format_username("tester", self.domain) incoming("+9991234567", "JOIN {} WORKER tester".format(self.domain), "TEST_CASE_BACKEND") # Test without mobile worker registration enabled self.assertIsNone(CommCareUser.get_by_username(formatted_username)) # Enable mobile worker registration setattr(self.domain_obj, "sms_mobile_worker_registration_enabled", True) self.domain_obj.save() incoming("+9991234567", "JOIN {} WORKER tester".format(self.domain), "TEST_CASE_BACKEND") self.assertIsNotNone(CommCareUser.get_by_username(formatted_username)) # Test a duplicate registration prev_num_users = num_mobile_users(self.domain) incoming("+9991234568", "JOIN {} WORKER tester".format(self.domain), "TEST_CASE_BACKEND") current_num_users = num_mobile_users(self.domain) self.assertEqual(prev_num_users, current_num_users)
class DeactivateScheduleTest(TransactionTestCase): def setUp(self): super(DeactivateScheduleTest, self).setUp() self.domain_1 = 'deactivate-schedules-1' self.domain_obj_1 = Domain(name=self.domain_1, uses_new_reminders=True) self.domain_obj_1.save() self.domain_2 = 'deactivate-schedules-2' self.domain_obj_2 = Domain(name=self.domain_2, uses_new_reminders=True) self.domain_obj_2.save() self.domain_1_sms_schedules = [ self.create_scheduled_broadcast(self.domain_1, SMSContent()), self.create_immediate_broadcast(self.domain_1, SMSContent()), self.create_conditional_alert(self.domain_1, SMSContent()), ] self.domain_1_survey_schedules = [ self.create_scheduled_broadcast(self.domain_1, self.create_survey_content()), self.create_immediate_broadcast(self.domain_1, self.create_survey_content()), self.create_conditional_alert(self.domain_1, self.create_survey_content()), ] self.domain_2_sms_schedules = [ self.create_scheduled_broadcast(self.domain_2, SMSContent()), self.create_immediate_broadcast(self.domain_2, SMSContent()), self.create_conditional_alert(self.domain_2, SMSContent()), ] self.domain_2_survey_schedules = [ self.create_scheduled_broadcast(self.domain_2, self.create_survey_content()), self.create_immediate_broadcast(self.domain_2, self.create_survey_content()), self.create_conditional_alert(self.domain_2, self.create_survey_content()), ] def create_survey_content(self): return SMSSurveyContent( form_unique_id='123', expire_after=60, ) def create_scheduled_broadcast(self, domain, content): schedule = TimedSchedule.create_simple_daily_schedule( domain, TimedEvent(time=time(12, 0)), content) return ScheduledBroadcast.objects.create( domain=domain, name='', start_date=date(2018, 1, 1), schedule=schedule, recipients=[['CommCareUser', uuid.uuid4().hex]], ) def create_immediate_broadcast(self, domain, content): schedule = AlertSchedule.create_simple_alert(domain, content) return ImmediateBroadcast.objects.create( domain=domain, name='', schedule=schedule, recipients=[['CommCareUser', uuid.uuid4().hex]], ) def create_conditional_alert(self, domain, content): schedule = AlertSchedule.create_simple_alert(domain, content) rule = create_empty_rule(domain, AutomaticUpdateRule.WORKFLOW_SCHEDULING) rule.add_action( CreateScheduleInstanceActionDefinition, alert_schedule_id=schedule.schedule_id, recipients=[['CommCareUser', uuid.uuid4().hex]], ) return rule def tearDown(self): for domain in (self.domain_1, self.domain_2): for rule in AutomaticUpdateRule.objects.filter(domain=domain): rule.hard_delete() for broadcast in ScheduledBroadcast.objects.filter(domain=domain): broadcast.delete() for broadcast in ImmediateBroadcast.objects.filter(domain=domain): broadcast.delete() for schedule in TimedSchedule.objects.filter(domain=domain): schedule.delete() for schedule in AlertSchedule.objects.filter(domain=domain): schedule.delete() self.domain_obj_1.delete() self.domain_obj_2.delete() super(DeactivateScheduleTest, self).tearDown() def assertScheduleActiveFlag(self, obj, active_flag): if isinstance(obj, ScheduledBroadcast): schedule = TimedSchedule.objects.get(schedule_id=obj.schedule_id) elif isinstance(obj, ImmediateBroadcast): schedule = AlertSchedule.objects.get(schedule_id=obj.schedule_id) elif isinstance(obj, AutomaticUpdateRule): schedule = AlertSchedule.objects.get( schedule_id=obj.get_messaging_rule_schedule().schedule_id) else: raise TypeError( "Expected ScheduledBroadcast, ImmediateBroadcast, or AutomaticUpdateRule" ) self.assertEqual(schedule.active, active_flag) def assertSchedulesActive(self, objects): for obj in objects: self.assertScheduleActiveFlag(obj, True) def assertSchedulesInactive(self, objects): for obj in objects: self.assertScheduleActiveFlag(obj, False) def test_deactivate_all_schedules(self): self.assertSchedulesActive(self.domain_1_sms_schedules) self.assertSchedulesActive(self.domain_1_survey_schedules) self.assertSchedulesActive(self.domain_2_sms_schedules) self.assertSchedulesActive(self.domain_2_survey_schedules) with patch('corehq.apps.accounting.subscription_changes.refresh_timed_schedule_instances.delay') as p1,\ patch('corehq.apps.accounting.subscription_changes.refresh_alert_schedule_instances.delay') as p2,\ patch('corehq.messaging.tasks.initiate_messaging_rule_run') as p3: _deactivate_schedules(self.domain_obj_1) self.assertEqual(p1.call_count, 2) p1.assert_has_calls([ call(broadcast.schedule_id, broadcast.recipients, start_date=broadcast.start_date) for broadcast in (self.domain_1_sms_schedules[0], self.domain_1_survey_schedules[0]) ], any_order=True) self.assertEqual(p2.call_count, 2) p2.assert_has_calls([ call(broadcast.schedule_id, broadcast.recipients) for broadcast in (self.domain_1_sms_schedules[1], self.domain_1_survey_schedules[1]) ], any_order=True) self.assertEqual(p3.call_count, 2) p3.assert_has_calls([ call(rule.domain, rule.pk) for rule in (self.domain_1_sms_schedules[2], self.domain_1_survey_schedules[2]) ], any_order=True) self.assertSchedulesInactive(self.domain_1_sms_schedules) self.assertSchedulesInactive(self.domain_1_survey_schedules) self.assertSchedulesActive(self.domain_2_sms_schedules) self.assertSchedulesActive(self.domain_2_survey_schedules) def test_deactivate_only_survey_schedules(self): self.assertSchedulesActive(self.domain_1_sms_schedules) self.assertSchedulesActive(self.domain_1_survey_schedules) self.assertSchedulesActive(self.domain_2_sms_schedules) self.assertSchedulesActive(self.domain_2_survey_schedules) with patch('corehq.apps.accounting.subscription_changes.refresh_timed_schedule_instances.delay') as p1,\ patch('corehq.apps.accounting.subscription_changes.refresh_alert_schedule_instances.delay') as p2,\ patch('corehq.messaging.tasks.initiate_messaging_rule_run') as p3: _deactivate_schedules(self.domain_obj_1, survey_only=True) b = self.domain_1_survey_schedules[0] p1.assert_called_once_with(b.schedule_id, b.recipients, start_date=b.start_date) b = self.domain_1_survey_schedules[1] p2.assert_called_once_with(b.schedule_id, b.recipients) rule = self.domain_1_survey_schedules[2] p3.assert_called_once_with(rule.domain, rule.pk) self.assertSchedulesActive(self.domain_1_sms_schedules) self.assertSchedulesInactive(self.domain_1_survey_schedules) self.assertSchedulesActive(self.domain_2_sms_schedules) self.assertSchedulesActive(self.domain_2_survey_schedules)
class TestUserRoleSubscriptionChanges(BaseAccountingTest): def setUp(self): super(TestUserRoleSubscriptionChanges, self).setUp() self.domain = Domain( name="test-sub-changes", is_active=True, ) self.domain.save() self.other_domain = Domain( name="other-domain", is_active=True, ) self.other_domain.save() UserRole.init_domain_with_presets(self.domain.name) self.user_roles = UserRole.by_domain(self.domain.name) self.custom_role = UserRole.get_or_create_with_permissions( self.domain.name, Permissions(edit_apps=True, edit_web_users=True), "Custom Role") self.custom_role.save() self.read_only_role = UserRole.get_read_only_role_by_domain( self.domain.name) self.admin_username = generator.create_arbitrary_web_user_name() self.web_users = [] self.commcare_users = [] for role in [self.custom_role] + self.user_roles: web_user = WebUser.create( self.other_domain.name, generator.create_arbitrary_web_user_name(), 'test123') web_user.is_active = True web_user.add_domain_membership(self.domain.name, role_id=role.get_id) web_user.save() self.web_users.append(web_user) commcare_user = generator.arbitrary_commcare_user( domain=self.domain.name) commcare_user.set_role(self.domain.name, role.get_qualified_id()) commcare_user.save() self.commcare_users.append(commcare_user) self.account = BillingAccount.get_or_create_account_by_domain( self.domain.name, created_by=self.admin_username)[0] self.advanced_plan = DefaultProductPlan.get_default_plan_version( edition=SoftwarePlanEdition.ADVANCED) def test_cancellation(self): subscription = Subscription.new_domain_subscription( self.account, self.domain.name, self.advanced_plan, web_user=self.admin_username) self._change_std_roles() subscription.change_plan(DefaultProductPlan.get_default_plan_version()) custom_role = UserRole.get(self.custom_role.get_id) self.assertTrue(custom_role.is_archived) # disable this part of the test until we improve the UX for notifying # downgraded users of their privilege changes # custom_web_user = WebUser.get(self.web_users[0].get_id) # custom_commcare_user = CommCareUser.get(self.commcare_users[0].get_id) # self.assertEqual( # custom_web_user.get_domain_membership(self.domain.name).role_id, # self.read_only_role.get_id # ) # self.assertIsNone( # custom_commcare_user.get_domain_membership(self.domain.name).role_id # ) self._assertInitialRoles() self._assertStdUsers() def test_resubscription(self): subscription = Subscription.new_domain_subscription( self.account, self.domain.name, self.advanced_plan, web_user=self.admin_username) self._change_std_roles() new_subscription = subscription.change_plan( DefaultProductPlan.get_default_plan_version()) custom_role = UserRole.get(self.custom_role.get_id) self.assertTrue(custom_role.is_archived) new_subscription.change_plan(self.advanced_plan, web_user=self.admin_username) custom_role = UserRole.get(self.custom_role.get_id) self.assertFalse(custom_role.is_archived) # disable this part of the test until we improve the UX for notifying # downgraded users of their privilege changes # custom_web_user = WebUser.get(self.web_users[0].get_id) # custom_commcare_user = CommCareUser.get(self.commcare_users[0].get_id) # self.assertEqual( # custom_web_user.get_domain_membership(self.domain.name).role_id, # self.read_only_role.get_id # ) # self.assertIsNone( # custom_commcare_user.get_domain_membership(self.domain.name).role_id # ) self._assertInitialRoles() self._assertStdUsers() def _change_std_roles(self): for u in self.user_roles: user_role = UserRole.get(u.get_id) user_role.permissions = Permissions(view_reports=True, edit_commcare_users=True, edit_locations=True, edit_apps=True, edit_data=True) user_role.save() def _assertInitialRoles(self): for u in self.user_roles: user_role = UserRole.get(u.get_id) self.assertEqual(user_role.permissions, UserRolePresets.get_permissions(user_role.name)) def _assertStdUsers(self): for ind, wu in enumerate(self.web_users[1:]): web_user = WebUser.get(wu.get_id) self.assertEqual( web_user.get_domain_membership(self.domain.name).role_id, self.user_roles[ind].get_id) for ind, cc in enumerate(self.commcare_users[1:]): commcare_user = CommCareUser.get(cc.get_id) self.assertEqual( commcare_user.get_domain_membership(self.domain.name).role_id, self.user_roles[ind].get_id) def tearDown(self): self.domain.delete() self.other_domain.delete() super(TestUserRoleSubscriptionChanges, self).tearDown()
class TestDeleteDomain(TestCase): def _create_data(self, domain_name, i): product = Product(domain=domain_name, name='test-{}'.format(i)) product.save() location = make_location( domain=domain_name, site_code='testcode-{}'.format(i), name='test-{}'.format(i), location_type='facility' ) location.save() report = StockReport.objects.create( type='balance', domain=domain_name, form_id='fake', date=datetime.utcnow(), server_date=datetime.utcnow(), ) StockTransaction.objects.create( report=report, product_id=product.get_id, sql_product=SQLProduct.objects.get(product_id=product.get_id), section_id='stock', type='stockonhand', case_id=location.linked_supply_point().get_id, stock_on_hand=100 ) SMS.objects.create(domain=domain_name) Call.objects.create(domain=domain_name) SQLLastReadMessage.objects.create(domain=domain_name) ExpectedCallback.objects.create(domain=domain_name) PhoneNumber.objects.create(domain=domain_name, is_two_way=False, pending_verification=False) event = MessagingEvent.objects.create( domain=domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) SelfRegistrationInvitation.objects.create( domain=domain_name, phone_number='999123', token=uuid.uuid4().hex, expiration_date=datetime.utcnow().date(), created_date=datetime.utcnow() ) backend = SQLMobileBackend.objects.create(domain=domain_name, is_global=False) SQLMobileBackendMapping.objects.create( domain=domain_name, backend_type=SQLMobileBackend.SMS, prefix=str(i), backend=backend ) MobileBackendInvitation.objects.create(domain=domain_name, backend=backend) def setUp(self): super(TestDeleteDomain, self).setUp() self.domain = Domain(name="test", is_active=True) self.domain.save() self.domain.convert_to_commtrack() self.current_subscription = Subscription.new_domain_subscription( BillingAccount.get_or_create_account_by_domain(self.domain.name, created_by='tests')[0], self.domain.name, DefaultProductPlan.get_default_plan_version(SoftwarePlanEdition.ADVANCED), date_start=date.today() - relativedelta(days=1), ) self.domain2 = Domain(name="test2", is_active=True) self.domain2.save() self.domain2.convert_to_commtrack() LocationType.objects.create( domain='test', name='facility', ) LocationType.objects.create( domain='test2', name='facility', ) LocationType.objects.create( domain='test', name='facility2', ) LocationType.objects.create( domain='test2', name='facility2', ) def _assert_sql_counts(self, domain, number): self.assertEqual(StockTransaction.objects.filter(report__domain=domain).count(), number) self.assertEqual(StockReport.objects.filter(domain=domain).count(), number) self.assertEqual(SQLLocation.objects.filter(domain=domain).count(), number) self.assertEqual(SQLProduct.objects.filter(domain=domain).count(), number) self.assertEqual(DocDomainMapping.objects.filter(domain_name=domain).count(), number) self.assertEqual(LocationType.objects.filter(domain=domain).count(), number) self.assertEqual(SMS.objects.filter(domain=domain).count(), number) self.assertEqual(Call.objects.filter(domain=domain).count(), number) self.assertEqual(SQLLastReadMessage.objects.filter(domain=domain).count(), number) self.assertEqual(ExpectedCallback.objects.filter(domain=domain).count(), number) self.assertEqual(PhoneNumber.objects.filter(domain=domain).count(), number) self.assertEqual(MessagingEvent.objects.filter(domain=domain).count(), number) self.assertEqual(MessagingSubEvent.objects.filter(parent__domain=domain).count(), number) self.assertEqual(SelfRegistrationInvitation.objects.filter(domain=domain).count(), number) self.assertEqual(SQLMobileBackend.objects.filter(domain=domain).count(), number) self.assertEqual(SQLMobileBackendMapping.objects.filter(domain=domain).count(), number) self.assertEqual(MobileBackendInvitation.objects.filter(domain=domain).count(), number) def test_sql_objects_deletion(self): for i in range(2): self._create_data('test', i) self._create_data('test2', i) self._assert_sql_counts('test', 2) self._assert_sql_counts('test2', 2) self.domain.delete() self._assert_sql_counts('test', 0) self._assert_sql_counts('test2', 2) def test_active_subscription_terminated(self): self.domain.delete() terminated_subscription = Subscription.visible_objects.get(subscriber__domain=self.domain.name) self.assertFalse(terminated_subscription.is_active) self.assertIsNotNone(terminated_subscription.date_end) def test_accounting_future_subscription_suppressed(self): self.current_subscription.date_end = self.current_subscription.date_start + relativedelta(days=5) self.current_subscription.save() next_subscription = Subscription.new_domain_subscription( self.current_subscription.account, self.domain.name, DefaultProductPlan.get_default_plan_version(edition=SoftwarePlanEdition.PRO), date_start=self.current_subscription.date_end, ) self.domain.delete() self.assertTrue( Subscription.visible_and_suppressed_objects.get( id=next_subscription.id ).is_hidden_to_ops ) def test_active_subscription_credits_transferred_to_account(self): credit_amount = random.randint(1, 10) CreditLine.add_credit( credit_amount, feature_type=FeatureType.SMS, subscription=self.current_subscription, ) self.domain.delete() subscription_credits = CreditLine.get_credits_by_subscription_and_features( self.current_subscription, feature_type=FeatureType.SMS, ) self.assertEqual(len(subscription_credits), 1) self.assertEqual(subscription_credits[0].balance, Decimal('0.0000')) account_credits = CreditLine.get_credits_for_account( self.current_subscription.account, feature_type=FeatureType.SMS, ) self.assertEqual(len(account_credits), 1) self.assertEqual(account_credits[0].balance, Decimal(credit_amount)) @patch('corehq.apps.accounting.models.DomainDowngradeActionHandler.get_response') def test_downgraded(self, mock_get_response): mock_get_response.return_value = True self.domain.delete() self.assertEqual(len(mock_get_response.call_args_list), 1) def _test_case_deletion(self): for domain_name in [self.domain.name, self.domain2.name]: CaseFactory(domain_name).create_case() self.assertEqual(len(CaseAccessors(domain_name).get_case_ids_in_domain()), 1) self.domain.delete() self.assertEqual(len(CaseAccessors(self.domain.name).get_case_ids_in_domain()), 0) self.assertEqual(len(CaseAccessors(self.domain2.name).get_case_ids_in_domain()), 1) @override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True) def test_case_deletion_sql(self): self._test_case_deletion() @override_settings(TESTS_SHOULD_USE_SQL_BACKEND=False) def test_case_deletion_couch(self): self._test_case_deletion() @override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True) def test_form_deletion(self): form_states = [state_tuple[0] for state_tuple in XFormInstanceSQL.STATES] for domain_name in [self.domain.name, self.domain2.name]: for form_state in form_states: create_form_for_test(domain_name, state=form_state) for doc_type in doc_type_to_state: self.assertEqual( len(FormAccessors(domain_name).get_all_form_ids_in_domain(doc_type=doc_type)), 1 ) self.domain.delete() for doc_type in doc_type_to_state: self.assertEqual( len(FormAccessors(self.domain.name).get_all_form_ids_in_domain(doc_type=doc_type)), 0 ) self.assertEqual( len(FormAccessors(self.domain2.name).get_all_form_ids_in_domain(doc_type=doc_type)), 1 ) def _assert_queryset_count(self, queryset_list, count): for queryset in queryset_list: self.assertEqual(queryset.count(), count) def _assert_aggregate_ucr_count(self, domain_name, count): self._assert_queryset_count([ AggregateTableDefinition.objects.filter(domain=domain_name), PrimaryColumn.objects.filter(table_definition__domain=domain_name), SecondaryTableDefinition.objects.filter(table_definition__domain=domain_name), SecondaryColumn.objects.filter(table_definition__table_definition__domain=domain_name), ], count) def test_aggregate_ucr_delete(self): for domain_name in [self.domain.name, self.domain2.name]: aggregate_table_definition = AggregateTableDefinition.objects.create( domain=domain_name, primary_data_source_id=uuid.uuid4(), table_id=random_hex(), ) secondary_table_definition = SecondaryTableDefinition.objects.create( table_definition=aggregate_table_definition, data_source_id=uuid.uuid4(), ) PrimaryColumn.objects.create(table_definition=aggregate_table_definition) SecondaryColumn.objects.create(table_definition=secondary_table_definition) self._assert_aggregate_ucr_count(domain_name, 1) self.domain.delete() self._assert_aggregate_ucr_count(self.domain.name, 0) self._assert_aggregate_ucr_count(self.domain2.name, 1) self.assertEqual(SecondaryTableDefinition.objects.count(), 1) self.assertEqual( SecondaryTableDefinition.objects.filter(table_definition__domain=self.domain2.name).count(), 1 ) self.assertEqual(PrimaryColumn.objects.count(), 1) self.assertEqual(PrimaryColumn.objects.filter(table_definition__domain=self.domain2.name).count(), 1) self.assertEqual(SecondaryColumn.objects.count(), 1) self.assertEqual( SecondaryColumn.objects.filter(table_definition__table_definition__domain=self.domain2.name).count(), 1 ) def _assert_calendar_fixture_count(self, domain_name, count): self._assert_queryset_count([ CalendarFixtureSettings.objects.filter(domain=domain_name) ], count) def test_calendar_fixture_counts(self): for domain_name in [self.domain.name, self.domain2.name]: CalendarFixtureSettings.objects.create(domain=domain_name, days_before=3, days_after=4) self._assert_calendar_fixture_count(domain_name, 1) self.domain.delete() self._assert_calendar_fixture_count(self.domain.name, 0) self._assert_calendar_fixture_count(self.domain2.name, 1) def _assert_case_importer_counts(self, domain_name, count): self._assert_queryset_count([ CaseUploadFormRecord.objects.filter(case_upload_record__domain=domain_name), CaseUploadRecord.objects.filter(domain=domain_name), ], count) def test_case_importer(self): for domain_name in [self.domain.name, self.domain2.name]: case_upload_record = CaseUploadRecord.objects.create( domain=domain_name, task_id=uuid.uuid4().hex, upload_id=uuid.uuid4().hex, ) CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record, form_id=random_hex(), ) self._assert_case_importer_counts(domain_name, 1) self.domain.delete() self._assert_case_importer_counts(self.domain.name, 0) self._assert_case_importer_counts(self.domain2.name, 1) self.assertEqual(CaseUploadFormRecord.objects.count(), 1) self.assertEqual( CaseUploadFormRecord.objects.filter(case_upload_record__domain=self.domain2.name).count(), 1 ) def _assert_case_search_counts(self, domain_name, count): self._assert_queryset_count([ CaseSearchConfig.objects.filter(domain=domain_name), CaseSearchQueryAddition.objects.filter(domain=domain_name), FuzzyProperties.objects.filter(domain=domain_name), IgnorePatterns.objects.filter(domain=domain_name), ], count) def test_case_search(self): for domain_name in [self.domain.name, self.domain2.name]: CaseSearchConfig.objects.create(domain=domain_name) CaseSearchQueryAddition.objects.create(domain=domain_name) FuzzyProperties.objects.create(domain=domain_name) IgnorePatterns.objects.create(domain=domain_name) self._assert_case_search_counts(domain_name, 1) self.domain.delete() self._assert_case_search_counts(self.domain.name, 0) self._assert_case_search_counts(self.domain2.name, 1) def _assert_data_analytics_counts(self, domain_name, count): self._assert_queryset_count([ GIRRow.objects.filter(domain_name=domain_name), MALTRow.objects.filter(domain_name=domain_name), ], count) def test_data_analytics(self): for domain_name in [self.domain.name, self.domain2.name]: GIRRow.objects.create( domain_name=domain_name, month=date.today(), start_date=date.today(), wams_current=1, active_users=1, using_and_performing=1, not_performing=1, inactive_experienced=1, inactive_not_experienced=1, not_experienced=1, not_performing_not_experienced=1, active_ever=1, possibly_exp=1, ever_exp=1, exp_and_active_ever=1, active_in_span=1, eligible_forms=1, ) MALTRow.objects.create( domain_name=domain_name, month=date.today(), num_of_forms=1, ) self._assert_data_analytics_counts(domain_name, 1) self.domain.delete() self._assert_data_analytics_counts(self.domain.name, 0) self._assert_data_analytics_counts(self.domain2.name, 1) def _assert_data_dictionary_counts(self, domain_name, count): self._assert_queryset_count([ CaseType.objects.filter(domain=domain_name), CaseProperty.objects.filter(case_type__domain=domain_name), ], count) def test_data_dictionary(self): for domain_name in [self.domain.name, self.domain2.name]: case_type = CaseType.objects.create(domain=domain_name, name='case_type') CaseProperty.objects.create(case_type=case_type, name='case_property') self._assert_data_dictionary_counts(domain_name, 1) self.domain.delete() self._assert_data_dictionary_counts(self.domain.name, 0) self._assert_data_dictionary_counts(self.domain2.name, 1) def _assert_data_interfaces(self, domain_name, count): self._assert_queryset_count([ AutomaticUpdateRule.objects.filter(domain=domain_name), CaseRuleAction.objects.filter(rule__domain=domain_name), CaseRuleCriteria.objects.filter(rule__domain=domain_name), CaseRuleSubmission.objects.filter(domain=domain_name), DomainCaseRuleRun.objects.filter(domain=domain_name), ], count) def test_data_interfaces(self): for domain_name in [self.domain.name, self.domain2.name]: automatic_update_rule = AutomaticUpdateRule.objects.create(domain=domain_name) CaseRuleAction.objects.create(rule=automatic_update_rule) CaseRuleCriteria.objects.create(rule=automatic_update_rule) CaseRuleSubmission.objects.create( created_on=datetime.utcnow(), domain=domain_name, form_id=random_hex(), rule=automatic_update_rule, ) DomainCaseRuleRun.objects.create(domain=domain_name, started_on=datetime.utcnow()) self._assert_data_interfaces(domain_name, 1) self.domain.delete() self._assert_data_interfaces(self.domain.name, 0) self._assert_data_interfaces(self.domain2.name, 1) self.assertEqual(CaseRuleAction.objects.count(), 1) self.assertEqual(CaseRuleAction.objects.filter(rule__domain=self.domain2.name).count(), 1) self.assertEqual(CaseRuleCriteria.objects.count(), 1) self.assertEqual(CaseRuleCriteria.objects.filter(rule__domain=self.domain2.name).count(), 1) def _assert_domain_counts(self, domain_name, count): self._assert_queryset_count([ TransferDomainRequest.objects.filter(domain=domain_name), ], count) def test_delete_domain(self): for domain_name in [self.domain.name, self.domain2.name]: TransferDomainRequest.objects.create(domain=domain_name, to_username='******', from_username='******') self._assert_domain_counts(domain_name, 1) self.domain.delete() self._assert_domain_counts(self.domain.name, 0) self._assert_domain_counts(self.domain2.name, 1) def _assert_export_counts(self, domain_name, count): self._assert_queryset_count([ DataFile.meta_query(domain_name), EmailExportWhenDoneRequest.objects.filter(domain=domain_name), ], count) def test_export_delete(self): blobdb = get_blob_db() data_files = [] for domain_name in [self.domain.name, self.domain2.name]: data_files.append(DataFile.save_blob( BytesIO((domain_name + " csv").encode('utf-8')), domain=domain_name, filename="data.csv", description="data file", content_type="text/csv", delete_after=datetime.utcnow() + timedelta(minutes=10), )) EmailExportWhenDoneRequest.objects.create(domain=domain_name) self._assert_export_counts(domain_name, 1) self.domain.delete() with self.assertRaises(NotFound): blobdb.get(key=data_files[0].blob_id) with blobdb.get(key=data_files[1].blob_id) as f: self.assertEqual(f.read(), (self.domain2.name + " csv").encode('utf-8')) self._assert_export_counts(self.domain.name, 0) self._assert_export_counts(self.domain2.name, 1) def _assert_location_counts(self, domain_name, count): self._assert_queryset_count([ LocationFixtureConfiguration.objects.filter(domain=domain_name) ], count) def test_location_delete(self): for domain_name in [self.domain.name, self.domain2.name]: LocationFixtureConfiguration.objects.create(domain=domain_name) self._assert_location_counts(domain_name, 1) self.domain.delete() self._assert_location_counts(self.domain.name, 0) self._assert_location_counts(self.domain2.name, 1) def _assert_ota_counts(self, domain_name, count): self._assert_queryset_count([ MobileRecoveryMeasure.objects.filter(domain=domain_name), SerialIdBucket.objects.filter(domain=domain_name), ], count) def test_ota_delete(self): for domain_name in [self.domain.name, self.domain2.name]: MobileRecoveryMeasure.objects.create(domain=domain_name) SerialIdBucket.objects.create(domain=domain_name) self._assert_ota_counts(domain_name, 1) self.domain.delete() self._assert_ota_counts(self.domain.name, 0) self._assert_ota_counts(self.domain2.name, 1) def _assert_reports_counts(self, domain_name, count): self._assert_queryset_count([ ReportsSidebarOrdering.objects.filter(domain=domain_name) ], count) def test_reports_delete(self): for domain_name in [self.domain.name, self.domain2.name]: ReportsSidebarOrdering.objects.create(domain=domain_name) self._assert_reports_counts(domain_name, 1) self.domain.delete() self._assert_reports_counts(self.domain.name, 0) self._assert_reports_counts(self.domain2.name, 1) def _assert_phone_counts(self, domain_name, count): self._assert_queryset_count([ OwnershipCleanlinessFlag.objects.filter(domain=domain_name), SyncLogSQL.objects.filter(domain=domain_name) ], count) def test_phone_delete(self): for domain_name in [self.domain.name, self.domain2.name]: OwnershipCleanlinessFlag.objects.create(domain=domain_name) SyncLogSQL.objects.create( domain=domain_name, doc={}, synclog_id=uuid.uuid4(), user_id=uuid.uuid4(), ) self._assert_phone_counts(domain_name, 1) self.domain.delete() self._assert_phone_counts(self.domain.name, 0) self._assert_phone_counts(self.domain2.name, 1) def _assert_reminders_counts(self, domain_name, count): self._assert_queryset_count([ EmailUsage.objects.filter(domain=domain_name), ], count) def test_reminders_delete(self): for domain_name in [self.domain.name, self.domain2.name]: EmailUsage.objects.create(domain=domain_name, month=7, year=2018) self._assert_reminders_counts(domain_name, 1) self.domain.delete() self._assert_reminders_counts(self.domain.name, 0) self._assert_reminders_counts(self.domain2.name, 1) def _assert_sms_counts(self, domain_name, count): self._assert_queryset_count([ DailyOutboundSMSLimitReached.objects.filter(domain=domain_name), Keyword.objects.filter(domain=domain_name), KeywordAction.objects.filter(keyword__domain=domain_name), QueuedSMS.objects.filter(domain=domain_name) ], count) def test_sms_delete(self): for domain_name in [self.domain.name, self.domain2.name]: DailyOutboundSMSLimitReached.objects.create(domain=domain_name, date=date.today()) keyword = Keyword.objects.create(domain=domain_name) KeywordAction.objects.create(keyword=keyword) QueuedSMS.objects.create(domain=domain_name) self._assert_sms_counts(domain_name, 1) self.domain.delete() self._assert_sms_counts(self.domain.name, 0) self._assert_sms_counts(self.domain2.name, 1) self.assertEqual(KeywordAction.objects.count(), 1) self.assertEqual(KeywordAction.objects.filter(keyword__domain=self.domain2.name).count(), 1) def _assert_smsforms_counts(self, domain_name, count): self._assert_queryset_count([ SQLXFormsSession.objects.filter(domain=domain_name), ], count) def test_smsforms_delete(self): for domain_name in [self.domain.name, self.domain2.name]: SQLXFormsSession.objects.create( domain=domain_name, start_time=datetime.utcnow(), modified_time=datetime.utcnow(), current_action_due=datetime.utcnow(), expire_after=3, ) self._assert_smsforms_counts(domain_name, 1) self.domain.delete() self._assert_smsforms_counts(self.domain.name, 0) self._assert_smsforms_counts(self.domain2.name, 1) def _assert_userreports_counts(self, domain_name, count): self._assert_queryset_count([ AsyncIndicator.objects.filter(domain=domain_name) ], count) def test_userreports_delete(self): for domain_name in [self.domain.name, self.domain2.name]: AsyncIndicator.objects.create( domain=domain_name, doc_id=random_hex(), doc_type='doc_type', indicator_config_ids=[], ) self._assert_userreports_counts(domain_name, 1) self.domain.delete() self._assert_userreports_counts(self.domain.name, 0) self._assert_userreports_counts(self.domain2.name, 1) def _assert_users_counts(self, domain_name, count): self._assert_queryset_count([ DomainRequest.objects.filter(domain=domain_name), ], count) def test_users_delete(self): for domain_name in [self.domain.name, self.domain2.name]: DomainRequest.objects.create(domain=domain_name, email='*****@*****.**', full_name='User') self._assert_users_counts(domain_name, 1) self.domain.delete() self._assert_users_counts(self.domain.name, 0) self._assert_users_counts(self.domain2.name, 1) def _assert_zapier_counts(self, domain_name, count): self._assert_queryset_count([ ZapierSubscription.objects.filter(domain=domain_name), ], count) def test_zapier_delete(self): for domain_name in [self.domain.name, self.domain2.name]: ZapierSubscription.objects.create( domain=domain_name, case_type='case_type', event_name=EventTypes.NEW_CASE, url='http://%s.com' % domain_name, user_id='user_id', ) self._assert_zapier_counts(domain_name, 1) self.domain.delete() self._assert_zapier_counts(self.domain.name, 0) self._assert_zapier_counts(self.domain2.name, 1) def _assert_motech_count(self, domain_name, count): self._assert_queryset_count([ RequestLog.objects.filter(domain=domain_name), ], count) def test_motech_delete(self): for domain_name in [self.domain.name, self.domain2.name]: RequestLog.objects.create(domain=domain_name) self._assert_motech_count(domain_name, 1) self.domain.delete() self._assert_motech_count(self.domain.name, 0) self._assert_motech_count(self.domain2.name, 1) def _assert_couchforms_counts(self, domain_name, count): self._assert_queryset_count([ UnfinishedSubmissionStub.objects.filter(domain=domain_name) ], count) def test_couchforms_delete(self): for domain_name in [self.domain.name, self.domain2.name]: UnfinishedSubmissionStub.objects.create( domain=domain_name, timestamp=datetime.utcnow(), xform_id='xform_id', ) self._assert_couchforms_counts(domain_name, 1) self.domain.delete() self._assert_couchforms_counts(self.domain.name, 0) self._assert_couchforms_counts(self.domain2.name, 1) def tearDown(self): self.domain2.delete() super(TestDeleteDomain, self).tearDown()