Exemple #1
0
class TestCaseListFilter(TestCase):
    def setUp(self):
        self.subject = CaseListFilter
        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).sql_location
        ]
        self.request = RequestFactory()
        self.request.couch_user = WebUser()
        self.request.domain = self.domain

    @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
Exemple #2
0
def request_new_domain(request, form, org, domain_type=None, new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user)

    commtrack_enabled = domain_type == 'commtrack'

    dom_req = RegistrationRequest()
    if new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    new_domain = Domain(
        name=form.cleaned_data['domain_name'],
        is_active=False,
        date_created=datetime.utcnow(),
        commtrack_enabled=commtrack_enabled,
        creating_user=current_user.username,
        secure_submissions=True,
    )

    if form.cleaned_data.get('domain_timezone'):
        new_domain.default_timezone = form.cleaned_data['domain_timezone']

    if org:
        new_domain.organization = org
        new_domain.hr_name = request.POST.get('domain_hrname', None) or new_domain.name

    if not new_user:
        new_domain.is_active = True

    # ensure no duplicate domain documents get created on cloudant
    new_domain.save(**get_safe_write_kwargs())

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save() # we need to get the name from the _id

    create_30_day_trial(new_domain)

    dom_req.domain = new_domain.name

    if request.user.is_authenticated():
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if new_user:
        dom_req.save()
        send_domain_registration_email(request.user.email,
                                       dom_req.domain,
                                       dom_req.activation_guid)
    else:
        send_global_domain_registration_email(request.user, new_domain.name)
    send_new_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=new_user)
Exemple #3
0
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()
Exemple #4
0
def create_user_and_domain(username='******', 
                           password='******',
                           domain_name='mockdomain'):
    """Creates a domain 'mockdomain' and a web user with name/pw 
       'brian'/'test'.  Returns these two objects in a tuple 
       as (domain, user).  The parameters are configurable."""
    try:
        domain = Domain.get_by_name(domain_name)
        print "WARNING: tried to create domain %s but it already exists!" % domain_name
        print "Are all your tests cleaning up properly?"
    except Domain.DoesNotExist:
        # this is the normal case
        domain = Domain(name=domain_name, is_active=True)
        domain.save()
    
    try:
        user = User.objects.get(username=username)
        print "WARNING: tried to create user %s but it already exists!" % username
        print "Are all your tests cleaning up properly?"
        # update the pw anyway
        user.password = _get_salted_pw(password)
        user.save()
    except User.DoesNotExist:
        user = User()
        user.username = username
        # here, we mimic what the django auth system does
        # only we specify the salt to be 12345
        user.password = _get_salted_pw(password)
        
        user.save()
        
    return (user, domain)
Exemple #5
0
def run():
    from django.contrib.sites.models import Site

    django_site_1 = Site.objects.all()[0]
    django_site_1.domain = u'localhost:8000'
    django_site_1.name = u'localhost:8000'
    django_site_1.save()

    from corehq.apps.domain.models import Domain

    domain_domain_1 = Domain()
    domain_domain_1.name = u'test'
    domain_domain_1.is_active = True
    domain_domain_1.save()

    from django.contrib.auth.models import User

    auth_user_1 = User()
    auth_user_1.username = u'admin'
    auth_user_1.first_name = u''
    auth_user_1.last_name = u''
    auth_user_1.email = u'*****@*****.**'
    auth_user_1.password = u'sha1$f8d4b$b6d2f6431c423687c227ad261caa46faaf16917d'
    auth_user_1.is_staff = True
    auth_user_1.is_active = True
    auth_user_1.is_superuser = True
    auth_user_1.last_login = datetime.datetime(2010, 9, 10, 14, 40, 30, 501416)
    auth_user_1.date_joined = datetime.datetime(2010, 9, 10, 14, 37, 22, 677987)
    auth_user_1.save()

    auth_user_2 = User()
    auth_user_2.username = u'test'
    auth_user_2.first_name = u'test'
    auth_user_2.last_name = u'test'
    auth_user_2.email = u'*****@*****.**'
    auth_user_2.password = u'sha1$f09cf$551ac80804020ad3e1d9943a583ee1ea52284797'
    auth_user_2.is_staff = False
    auth_user_2.is_active = True
    auth_user_2.is_superuser = False
    auth_user_2.last_login = datetime.datetime(2010, 9, 10, 14, 40, 53, 818764)
    auth_user_2.date_joined = datetime.datetime(2010, 9, 10, 19, 40, 6, 159442)
    auth_user_2.save()

    couch_user = auth_user_2.get_profile().get_couch_user()
    couch_user.add_domain_membership(domain_domain_1.name)
    couch_user.save()

    from corehq.apps.domain.models import RegistrationRequest

    domain_registration_request_1 = RegistrationRequest()
    domain_registration_request_1.tos_confirmed = True
    domain_registration_request_1.request_time = datetime.datetime(2010, 9, 10, 19, 40, 6, 159442)
    domain_registration_request_1.request_ip = '127.0.0.1'
    domain_registration_request_1.activation_guid = u'368ce6b8bd1311df932c5cff350164a3'
    domain_registration_request_1.confirm_time = datetime.datetime(2010, 9, 10, 14, 40, 25, 219783)
    domain_registration_request_1.confirm_ip = '127.0.0.1'
    domain_registration_request_1.domain = domain_domain_1
    domain_registration_request_1.new_user = auth_user_2
    domain_registration_request_1.requesting_user = None
    domain_registration_request_1.save()
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()
Exemple #7
0
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 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)
Exemple #8
0
class UpdateTestCase(TestCase):

    def setUp(self):
        super(UpdateTestCase, self).setUp()
        delete_all_users()
        self.username = "******"
        password = "******"
        self.domain = Domain(name='my-domain')
        self.domain.save()
        self.couch_user = CommCareUser.create(self.domain.name, self.username, password)
        self.couch_user.save()
        
    def testAddRemovePhoneNumbers(self):
        """ 
        test that a basic couch user gets created properly after 
        saving a django user programmatically
        """
        self.couch_user.add_phone_number('123123123')
        self.assertEqual(self.couch_user.phone_numbers, ['123123123'])
        self.couch_user.add_phone_number('321321321')
        self.assertEqual(self.couch_user.phone_numbers, ['123123123', '321321321'])

    def testChangeUsername(self):
        new_username = '******'
        self.assertEqual(CouchUser.get_by_username(self.username).user_id, self.couch_user.user_id)
        self.assertEqual(User.objects.filter(username=self.username).count(), 1)
        self.couch_user.change_username(new_username)
        self.assertEqual(CouchUser.get_by_username(self.username), None)
        self.assertEqual(CouchUser.get_by_username(new_username).user_id, self.couch_user.user_id)
        self.assertEqual(self.couch_user.get_django_user().username, new_username)
        self.assertEqual(User.objects.filter(username=new_username).count(), 1)
        self.assertEqual(User.objects.get(username=new_username).id, self.couch_user.get_django_user().id)
        self.assertEqual(User.objects.filter(username=self.username).count(), 0)
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)
Exemple #10
0
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()
def arbitrary_domain():
    domain = Domain(
        name=data_gen.arbitrary_unique_name()[:20],
        is_active=True,
    )
    domain.save()
    return domain
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)
Exemple #13
0
    def create_domain(self, domain):
        domain_obj = Domain(name=domain)
        domain_obj.use_default_sms_response = True
        domain_obj.default_sms_response = "Default SMS Response"
        domain_obj.save()

        # I tried making this class inherit from BaseSMSTest, but somehow
        # the multiple inheritance was causing the postgres connection to
        # get in a weird state where it wasn't commiting any changes. So
        # for now, keeping this subscription setup code as is.
        generator.instantiate_accounting_for_tests()
        self.account = BillingAccount.get_or_create_account_by_domain(
            domain_obj.name,
            created_by="automated-test",
        )[0]
        plan = DefaultProductPlan.get_default_plan_by_domain(
            domain_obj, edition=SoftwarePlanEdition.ADVANCED
        )
        self.subscription = Subscription.new_domain_subscription(
            self.account,
            domain_obj.name,
            plan
        )
        self.subscription.is_active = True
        self.subscription.save()
        return domain_obj
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 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 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 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()
Exemple #18
0
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()
Exemple #19
0
    def create_domain(self, domain):
        domain_obj = Domain(name=domain)
        domain_obj.use_default_sms_response = True
        domain_obj.default_sms_response = "Default SMS Response"
        domain_obj.save()

        self.setup_subscription(domain_obj.name, SoftwarePlanEdition.ADVANCED)
        return domain_obj
Exemple #20
0
 def test_should_sync_hierarchical_format_if_location_types_exist(self):
     domain = uuid.uuid4().hex
     project = Domain(name=domain)
     project.save()
     location_type = LocationType.objects.create(domain=domain, name='test-type')
     self.assertEqual(True, should_sync_hierarchical_fixture(project))
     self.addCleanup(project.delete)
     self.addCleanup(location_type.delete)
Exemple #21
0
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)
Exemple #22
0
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)
    def setUpClass(cls):
        domain_foo = Domain(name='foo')
        domain_foo.save()
        domain_bar = Domain(name='bar')
        domain_bar.save()

        ReportConfiguration(domain=domain_foo.name, config_id='foo1').save()
        ReportConfiguration(domain=domain_foo.name, config_id='foo2').save()
        ReportConfiguration(domain=domain_bar.name, config_id='bar1').save()
 def test_should_sync_hierarchical_format_if_location_types_exist(self):
     domain = uuid.uuid4().hex
     project = Domain(name=domain)
     project.save()
     location_type = LocationType.objects.create(domain=domain,
                                                 name='test-type')
     self.assertEqual(True, should_sync_hierarchical_fixture(project))
     self.addCleanup(project.delete)
     self.addCleanup(location_type.delete)
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])
Exemple #26
0
 def dispatch(self, request, *args, **kwargs):
     # HACK HACK HACK HACK HACK from Tim, just moving it over
     # todo fix HACK HACK HACK HACK HACK
     dummy = Domain.get_by_name("dumdum")
     if not dummy:
         dummy = Domain(name="dumdum", is_active=True, date_created=datetime.datetime.utcnow())
         dummy.save()
     kwargs["domain"] = "dumdum"
     return super(AppstoreDispatcher, self).dispatch(request, *args, **kwargs)
Exemple #27
0
def request_new_domain(request, form, org, domain_type=None, new_user=True):
    now = datetime.utcnow()
    current_user = CouchUser.from_django_user(request.user)

    commtrack_enabled = domain_type == 'commtrack'

    dom_req = RegistrationRequest()
    if new_user:
        dom_req.request_time = now
        dom_req.request_ip = get_ip(request)
        dom_req.activation_guid = uuid.uuid1().hex

    new_domain = Domain(name=form.cleaned_data['domain_name'],
                        is_active=False,
                        date_created=datetime.utcnow(),
                        commtrack_enabled=commtrack_enabled,
                        creating_user=current_user.username)

    bootstrap_default(new_domain)

    if org:
        new_domain.organization = org
        new_domain.hr_name = request.POST.get('domain_hrname',
                                              None) or new_domain.name

    if not new_user:
        new_domain.is_active = True

    # ensure no duplicate domain documents get created on cloudant
    new_domain.save(**get_safe_write_kwargs())

    if not new_domain.name:
        new_domain.name = new_domain._id
        new_domain.save()  # we need to get the name from the _id

    dom_req.domain = new_domain.name

    if request.user.is_authenticated():
        if not current_user:
            current_user = WebUser()
            current_user.sync_from_django_user(request.user)
            current_user.save()
        current_user.add_domain_membership(new_domain.name, is_admin=True)
        current_user.save()
        dom_req.requesting_user_username = request.user.username
        dom_req.new_user_username = request.user.username

    if new_user:
        dom_req.save()
        send_domain_registration_email(request.user.email, dom_req.domain,
                                       dom_req.activation_guid)
    else:
        send_global_domain_registration_email(request.user, new_domain.name)
    send_new_domain_request_update_email(request.user,
                                         get_ip(request),
                                         new_domain.name,
                                         is_new_user=new_user)
Exemple #28
0
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 setUpClass(cls):
        super(ReportConfigurationDbTest, cls).setUpClass()
        domain_foo = Domain(name='foo')
        domain_foo.save()
        domain_bar = Domain(name='bar')
        domain_bar.save()

        ReportConfiguration(domain=domain_foo.name, config_id='foo1').save()
        ReportConfiguration(domain=domain_foo.name, config_id='foo2').save()
        ReportConfiguration(domain=domain_bar.name, config_id='bar1').save()
Exemple #30
0
 def test_wrong_domain(self):
     other_domain = Domain(name='other_domain')
     other_domain.save()
     self.addCleanup(other_domain.delete)
     correct_credentials = self._get_correct_credentials()
     response = self.client.get(
         reverse(self.view_urlname, kwargs={'domain': other_domain.name}),
         HTTP_AUTHORIZATION='Basic ' + correct_credentials,
     )
     self.assertEqual(response.status_code, 403)
Exemple #31
0
    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()
Exemple #32
0
 def test_wrong_domain(self):
     other_domain = Domain(name='other_domain')
     other_domain.save()
     self.addCleanup(other_domain.delete)
     correct_credentials = self._get_correct_credentials()
     response = self.client.get(
         reverse(self.view_urlname, kwargs={'domain': other_domain.name}),
         HTTP_AUTHORIZATION='Basic ' + correct_credentials,
     )
     self.assertEqual(response.status_code, 403)
Exemple #33
0
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 TestRenewSubscriptions(BaseAccountingTest):

    def setUp(self):
        super(TestRenewSubscriptions, self).setUp()
        self.domain = Domain(
            name="test-domain-sub",
            is_active=True,
        )
        self.domain.save()

        self.admin_user = generator.arbitrary_web_user()
        self.admin_user.add_domain_membership(self.domain.name, is_admin=True)
        self.admin_user.save()

        self.account = BillingAccount.get_or_create_account_by_domain(
            self.domain.name, created_by=self.admin_user.username)[0]

        self.standard_plan = DefaultProductPlan.get_default_plan_by_domain(
            self.domain.name, edition=SoftwarePlanEdition.STANDARD)

        today = datetime.date.today()
        yesterday = today + datetime.timedelta(days=-1)
        tomorrow = today + datetime.timedelta(days=1)

        self.subscription = Subscription.new_domain_subscription(
            self.account,
            self.domain.name,
            self.standard_plan,
            web_user=self.admin_user.username,
            date_start=yesterday,
            date_end=tomorrow,
        )

        self.subscription.save()

    def test_simple_renewal(self):
        today = datetime.date.today()

        renewed_subscription = self.subscription.renew_subscription()

        self.assertEqual(renewed_subscription.date_end, None)
        self.assertEqual(renewed_subscription.date_start, self.subscription.date_end)
        self.assertEqual(renewed_subscription.plan_version, self.subscription.plan_version)

    def test_change_plan_on_renewal(self):
        today = datetime.date.today()
        new_edition = SoftwarePlanEdition.ADVANCED
        new_plan = DefaultProductPlan.get_default_plan_by_domain(self.domain.name, new_edition)

        renewed_subscription = self.subscription.renew_subscription(
            new_version=new_plan
        )

        self.assertEqual(renewed_subscription.plan_version, new_plan)
Exemple #37
0
    def test_wrong_domain(self):
        other_domain = Domain(name='other_domain')
        other_domain.save()
        self.addCleanup(other_domain.delete)

        correct_credentials = self._get_correct_credentials()
        response = self.client.get(
            self._odata_feed_url_by_domain(other_domain.name),
            HTTP_AUTHORIZATION='Basic ' + correct_credentials,
        )
        self.assertEqual(response.status_code, 404)
Exemple #38
0
    def test_wrong_domain(self):
        other_domain = Domain(name='other_domain')
        other_domain.save()
        self.addCleanup(other_domain.delete)

        correct_credentials = self._get_correct_credentials()
        response = self.client.get(
            self._odata_feed_url_by_domain(other_domain.name),
            HTTP_AUTHORIZATION='Basic ' + correct_credentials,
        )
        self.assertEqual(response.status_code, 404)
Exemple #39
0
 def dispatch(self, request, *args, **kwargs):
     # HACK HACK HACK HACK HACK from Tim, just moving it over
     # todo fix HACK HACK HACK HACK HACK
     dummy = Domain.get_by_name('dumdum')
     if not dummy:
         dummy = Domain(name='dumdum',
                        is_active=True,
                        date_created=datetime.datetime.utcnow())
         dummy.save()
     kwargs['domain'] = 'dumdum'
     return super(AppstoreDispatcher,
                  self).dispatch(request, *args, **kwargs)
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 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 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 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)
Exemple #44
0
def arbitrary_web_user(save=True, is_dimagi=False):
    domain = Domain(name=unique_name()[:25])
    domain.save()
    username = "******" % (unique_name(),
                              'dimagi' if is_dimagi else 'gmail')
    try:
        web_user = WebUser.create(domain.name, username, 'test123')
    except Exception:
        web_user = WebUser.get_by_username(username)
    web_user.is_active = True
    if save:
        web_user.save()
    return web_user
Exemple #45
0
    def setUp(self):
        super(ReportConfigurationDbTest, self).setUp()
        domain_foo = Domain(name='foo')
        domain_foo.save()
        domain_bar = Domain(name='bar')
        domain_bar.save()

        # TODO - handle cleanup appropriately so this isn't needed
        delete_all_report_configs()

        ReportConfiguration(domain=domain_foo.name, config_id='foo1').save()
        ReportConfiguration(domain=domain_foo.name, config_id='foo2').save()
        ReportConfiguration(domain=domain_bar.name, config_id='bar1').save()
 def test_should_sync_hierarchical_format_disabled(self):
     domain = uuid.uuid4().hex
     project = Domain(name=domain)
     project.save()
     location_type = LocationType.objects.create(domain=domain,
                                                 name='test-type')
     location_settings = LocationFixtureConfiguration.objects.create(
         domain=domain, sync_hierarchical_fixture=False)
     self.assertEqual(False, should_sync_hierarchical_fixture(project))
     with flag_enabled('FLAT_LOCATION_FIXTURE'):
         self.assertEqual(False, should_sync_hierarchical_fixture(project))
     self.addCleanup(project.delete)
     self.addCleanup(location_type.delete)
     self.addCleanup(location_settings.delete)
    def test_can_edit_report(self):
        """
        Test whether ConfigurableReportView.page_context allows report editing
        """
        domain = Domain(name='test_domain', is_active=True)
        domain.save()
        self.addCleanup(domain.delete)

        def create_view(can_edit_reports):
            rolename = 'edit_role' if can_edit_reports else 'view_role'
            username = '******' if can_edit_reports else 'viewer'
            toggles.USER_CONFIGURABLE_REPORTS.set(username, True, toggles.NAMESPACE_USER)

            user_role = UserRole(
                domain=domain.name,
                name=rolename,
                permissions=Permissions(edit_commcare_users=True,
                                        view_commcare_users=True,
                                        edit_groups=True,
                                        view_groups=True,
                                        edit_locations=True,
                                        view_locations=True,
                                        access_all_locations=False,
                                        edit_data=True,
                                        edit_reports=can_edit_reports,
                                        view_reports=True
                                        )
            )
            user_role.save()
            # user_role should be deleted along with the domain.

            web_user = WebUser.create(domain.name, username, '***', None, None)
            web_user.set_role(domain.name, user_role.get_qualified_id())
            web_user.current_domain = domain.name
            web_user.save()
            self.addCleanup(web_user.delete, deleted_by=None)

            request = HttpRequest()
            request.can_access_all_locations = True
            request.user = web_user.get_django_user()
            request.couch_user = web_user
            request.session = {}
            _, view = self._build_report_and_view(request=request)
            return view

        cannot_edit_view = create_view(False)
        self.assertEqual(cannot_edit_view.page_context['can_edit_report'], False)

        can_edit_view = create_view(True)
        self.assertEqual(can_edit_view.page_context['can_edit_report'], True)
Exemple #48
0
    def setup_domain(cls, name):
        domain_obj = Domain(name=name, sms_mobile_worker_registration_enabled=True)
        domain_obj.save()

        plan = DefaultProductPlan.get_default_plan_version(edition=SoftwarePlanEdition.ADVANCED)
        account = BillingAccount.get_or_create_account_by_domain(
            name, created_by="automated-test-" + cls.__name__
        )[0]
        subscription = Subscription.new_domain_subscription(account, name, plan)
        subscription.is_active = True
        subscription.save()

        domain_obj = Domain.get(domain_obj.get_id)
        return (domain_obj, account, subscription)
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 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])
Exemple #51
0
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()
Exemple #52
0
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]
Exemple #53
0
class UpdateTestCase(TestCase):
    def setUp(self):
        all_users = CouchUser.all()
        for user in all_users:
            user.delete()
        User.objects.all().delete()
        self.username = "******"
        password = "******"
        self.domain = Domain(name='my-domain')
        self.domain.save()
        self.couch_user = CommCareUser.create(self.domain.name, self.username,
                                              password)
        self.couch_user.save()

    def testAddRemovePhoneNumbers(self):
        """ 
        test that a basic couch user gets created properly after 
        saving a django user programmatically
        """
        self.couch_user.add_phone_number('123123123')
        self.assertEqual(self.couch_user.phone_numbers, ['123123123'])
        self.couch_user.add_phone_number('321321321')
        self.assertEqual(self.couch_user.phone_numbers,
                         ['123123123', '321321321'])

    def testChangeUsername(self):
        new_username = '******'
        self.assertEqual(
            CouchUser.get_by_username(self.username).user_id,
            self.couch_user.user_id)
        self.assertEqual(
            User.objects.filter(username=self.username).count(), 1)
        self.couch_user.change_username(new_username)
        self.assertEqual(CouchUser.get_by_username(self.username), None)
        self.assertEqual(
            CouchUser.get_by_username(new_username).user_id,
            self.couch_user.user_id)
        self.assertEqual(self.couch_user.get_django_user().username,
                         new_username)
        self.assertEqual(User.objects.filter(username=new_username).count(), 1)
        self.assertEqual(
            User.objects.get(username=new_username).id,
            self.couch_user.get_django_user().id)
        self.assertEqual(
            User.objects.filter(username=self.username).count(), 0)
Exemple #54
0
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)
    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)
Exemple #56
0
class StateHashTest(TestCase):
    def setUp(self):
        delete_all_cases()
        delete_all_xforms()
        delete_all_sync_logs()
        delete_all_users()
        self.project = Domain(name='state-hash-tests-project')
        self.project.save()
        self.user = create_restore_user(domain=self.project.name)

        # this creates the initial blank sync token in the database
        generate_restore_payload(self.project, self.user)
        self.sync_log = get_exactly_one_wrapped_sync_log()

    @run_with_all_backends
    def testEmpty(self):
        empty_hash = CaseStateHash(EMPTY_HASH)
        wrong_hash = CaseStateHash("thisisntright")
        self.assertEqual(empty_hash, self.sync_log.get_state_hash())
        response = generate_restore_response(self.project,
                                             self.user,
                                             self.sync_log.get_id,
                                             version=V2)
        self.assertEqual(200, response.status_code)

        try:
            generate_restore_payload(self.project,
                                     self.user,
                                     self.sync_log.get_id,
                                     version=V2,
                                     state_hash=str(wrong_hash))
            self.fail(
                "Call to generate a payload with a bad hash should fail!")
        except BadStateException, e:
            self.assertEqual(empty_hash, e.server_hash)
            self.assertEqual(wrong_hash, e.phone_hash)
            self.assertEqual(0, len(e.case_ids))

        response = generate_restore_response(self.project,
                                             self.user,
                                             self.sync_log.get_id,
                                             version=V2,
                                             state_hash=str(wrong_hash))
        self.assertEqual(412, response.status_code)
Exemple #57
0
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)
    def test_sync_format_with_disabled_toggle(self):
        domain = uuid.uuid4().hex
        project = Domain(name=domain)
        project.save()

        self.assertEqual(False, should_sync_hierarchical_fixture(project))
        self.assertEqual(True, should_sync_flat_fixture(project))

        # This should not happen ideally since the conf can not be set without having HIERARCHICAL_LOCATION_FIXTURE
        # enabled. Considering that a domain has sync hierarchical fixture set to False without the FF
        # HIERARCHICAL_LOCATION_FIXTURE. In such case the domain stays on flat fixture format
        conf = LocationFixtureConfiguration.for_domain(domain)
        conf.sync_hierarchical_fixture = False
        conf.sync_flat_fixture = True  # default value
        conf.save()

        self.assertEqual(False, should_sync_hierarchical_fixture(project))
        self.assertEqual(True, should_sync_flat_fixture(project))

        self.addCleanup(project.delete)
    def test_web_user(self):
        from corehq.apps.users.models import WebUser
        other_domain = Domain(name='other-domain')
        other_domain.save()
        self.addCleanup(other_domain.delete)

        web_user = WebUser.create(
            domain=self.domain_name,
            username='******',
            password='******',
            email='*****@*****.**',
        )
        other_user = WebUser.create(
            domain='other-domain',
            username='******',
            password='******',
            email='*****@*****.**',
        )

        self._dump_and_load([web_user], [other_user])