def setUpClass(cls): cls.domain = 'supply-point-dbaccessors' cls.locations = [ Location(domain=cls.domain), Location(domain=cls.domain), Location(domain=cls.domain), ] Location.get_db().bulk_save(cls.locations) cls.supply_points = [ CommCareCase(domain=cls.domain, type='supply-point', location_id=cls.locations[0]._id), CommCareCase(domain=cls.domain, type='supply-point', location_id=cls.locations[1]._id), CommCareCase(domain=cls.domain, type='supply-point', location_id=cls.locations[2]._id), ] locations_by_id = { location._id: location for location in cls.locations } cls.location_supply_point_pairs = [ (locations_by_id[supply_point.location_id], supply_point) for supply_point in cls.supply_points ] CommCareCase.get_db().bulk_save(cls.supply_points)
def setUp(self): now = datetime.utcnow() owner_id = str(uuid4()) self.parent_case_id = str(uuid4()) self.parent_case = CommCareCase( _id=self.parent_case_id, domain=DOMAIN, type='person', name='Beth', owner_id=owner_id, modified_on=now, server_modified_on=now, ) self.parent_case.save() self.child_case_id = str(uuid4()) self.child_case = CommCareCase( _id=self.child_case_id, domain=DOMAIN, type='vitals', temperature=36.1, indices=[ CommCareCaseIndex( identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, ) ], owner_id=owner_id, modified_on=now, server_modified_on=now, ) self.child_case.save()
def setUpClass(cls): super(DBAccessorsTest, cls).setUpClass() cls.domain = 'lalksdjflakjsdf' cases = [ CommCareCase(domain=cls.domain, type='type1', name='Alice', user_id='XXX', prop_a=True, prop_b=True), CommCareCase(domain=cls.domain, type='type2', name='Bob', user_id='XXX', prop_a=True, prop_c=True), CommCareCase(domain=cls.domain, type='type1', name='Candice', user_id='ZZZ'), CommCareCase(domain=cls.domain, type='type1', name='Derek', user_id='XXX', closed=True), CommCareCase(domain='maleficent', type='type1', name='Mallory', user_id='YYY', prop_y=True) ] cls.forms, cls.cases = create_real_cases_from_dummy_cases(cases) assert len(cls.cases) == len(cases)
class TestCheckActionOrder(TestCase): def test(self): case = CommCareCase(actions=[ CommCareCaseAction(server_date=datetime(2001, 01, 01, 00, 00, 00)), CommCareCaseAction(server_date=datetime(2001, 01, 02, 00, 00, 00)), CommCareCaseAction(server_date=datetime(2001, 01, 03, 00, 00, 00)), ]) self.assertTrue(case.check_action_order()) case = CommCareCase(actions=[ CommCareCaseAction(server_date=datetime(2001, 01, 01, 00, 00, 00)), CommCareCaseAction(server_date=datetime(2001, 01, 03, 00, 00, 00)), CommCareCaseAction(server_date=datetime(2001, 01, 02, 00, 00, 00)), ]) self.assertFalse(case.check_action_order()) case = CommCareCase(actions=[ CommCareCaseAction(server_date=datetime(2001, 01, 01, 00, 00, 00)), CommCareCaseAction(server_date=None), CommCareCaseAction(server_date=datetime(2001, 01, 02, 00, 00, 00)), CommCareCaseAction(server_date=datetime(2001, 01, 03, 00, 00, 00)), ]) self.assertTrue(case.check_action_order()) case = CommCareCase(actions=[ CommCareCaseAction(server_date=datetime(2001, 01, 01, 00, 00, 00)), CommCareCaseAction(server_date=datetime(2001, 01, 03, 00, 00, 00)), CommCareCaseAction(server_date=None), CommCareCaseAction(server_date=datetime(2001, 01, 02, 00, 00, 00)), ]) self.assertFalse(case.check_action_order())
def setUpClass(cls): cls.domain = 'skbanskdjoasdkng' cls.cases = [ CommCareCase(name='A', domain=cls.domain), CommCareCase(name='B', domain=cls.domain), CommCareCase(name='C', domain=cls.domain), CommCareCase(name='D', domain=cls.domain), CommCareCase(name='X', domain='bunny'), ] CommCareCase.get_db().bulk_save(cls.cases) cls.case_groups = [ CommCareCaseGroup(name='alpha', domain=cls.domain, cases=[cls.cases[0]._id, cls.cases[1]._id]), CommCareCaseGroup(name='beta', domain=cls.domain, cases=[cls.cases[2]._id, cls.cases[3]._id]), CommCareCaseGroup(name='gamma', domain=cls.domain, cases=[cls.cases[0]._id, cls.cases[3]._id]), CommCareCaseGroup(name='delta', domain=cls.domain, cases=[cls.cases[1]._id, cls.cases[2]._id]), ] CommCareCaseGroup.get_db().bulk_save(cls.case_groups)
def testOTASettings(self): ct_settings = CommtrackConfig.for_domain(self.domain) ct_settings.consumption_config = ConsumptionConfig( min_transactions=10, min_window=20, optimal_window=60, ) ct_settings.ota_restore_config = StockRestoreConfig( section_to_consumption_types={'stock': 'consumption'}, ) set_default_monthly_consumption_for_domain(self.domain, 5 * DAYS_IN_MONTH) restore_settings = ct_settings.get_ota_restore_settings() self.assertEqual(1, len(restore_settings.section_to_consumption_types)) self.assertEqual('consumption', restore_settings.section_to_consumption_types['stock']) self.assertEqual(10, restore_settings.consumption_config.min_periods) self.assertEqual(20, restore_settings.consumption_config.min_window) self.assertEqual(60, restore_settings.consumption_config.max_window) self.assertEqual(150, restore_settings.consumption_config.default_monthly_consumption_function('foo', 'bar')) self.assertFalse(restore_settings.force_consumption_case_filter(CommCareCase(type='force-type'))) self.assertEqual(0, len(restore_settings.default_product_list)) ct_settings.ota_restore_config.force_consumption_case_types=['force-type'] ct_settings.ota_restore_config.use_dynamic_product_list=True restore_settings = ct_settings.get_ota_restore_settings() self.assertTrue(restore_settings.force_consumption_case_filter(CommCareCase(type='force-type'))) self.assertEqual(3, len(restore_settings.default_product_list))
class DBAccessorsTest(TestCase): @classmethod def setUpClass(cls): super(DBAccessorsTest, cls).setUpClass() cls.domain = 'domain-domain' cls.project = create_domain(cls.domain) cls.db = get_db() @classmethod def tearDownClass(cls): super(DBAccessorsTest, cls).tearDownClass() for snapshot in cls.project.snapshots(): snapshot.delete() cls.project.delete() def test_get_doc_count_in_domain_by_class(self): case = CommCareCase(domain=self.domain, opened_on=datetime.datetime(2000, 1, 1)) case.save() self.addCleanup(case.delete) case2 = CommCareCase(domain=self.domain, opened_on=datetime.datetime(2001, 1, 1)) case2.save() self.addCleanup(case2.delete) get = functools.partial( get_doc_count_in_domain_by_class, self.domain, CommCareCase) self.assertEqual(get(), 2)
def setUp(self): now = datetime.utcnow() self.parent_case_id = str(uuid4()) self.parent_case = CommCareCase( _id=self.parent_case_id, domain=DOMAIN, type='person', name='Ted', owner_id=str(uuid4()), modified_on=now, server_modified_on=now, ) self.parent_case.save() self.child_case_1 = CommCareCase( case_id='111111111', domain=DOMAIN, type='person_name', name='Theodore', given_names='Theodore John', family_name='Kaczynski', indices=[ CommCareCaseIndex( identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, ) ], owner_id=str(uuid4()), modified_on=now, server_modified_on=now, ) self.child_case_1.save() self.child_case_2 = CommCareCase( case_id='222222222', domain=DOMAIN, type='person_name', name='Unabomber', given_names='Unabomber', indices=[ CommCareCaseIndex( identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, ) ], owner_id=str(uuid4()), modified_on=now, server_modified_on=now, ) self.child_case_2.save()
def test_complex_index(self): cp = CommCareCase( _id='parent', name='parent', type='parent', ) cp.save() # cases processed according to ID order so ensure that this case is # processed after the task case by making its ID sort after task ID cc = CommCareCase( _id='z_goal', name='goal', type='goal', indices=[ CommCareCaseIndex(identifier='parent', referenced_type='parent', referenced_id='parent') ], ) cc.save() cc = CommCareCase( _id='task1', name='task1', type='task', indices=[ CommCareCaseIndex(identifier='goal', referenced_type='goal', referenced_id='z_goal'), CommCareCaseIndex(identifier='parent', referenced_type='parent', referenced_id='parent') ], ) cc.save() # with 'ignore_relationship_types' if a case got processed along the ignored relationship first # then it got marked as 'seen' and would be not be processed again when it came to the correct relationship type_info = { 'task': { 'ignore_relationship_types': ['parent'] }, } hierarchy = get_case_hierarchy(cp, type_info) self.assertEqual(3, len(hierarchy['case_list'])) self.assertEqual(1, len(hierarchy['child_cases'])) self.assertEqual(2, len(hierarchy['child_cases'][0]['case_list'])) self.assertEqual(1, len(hierarchy['child_cases'][0]['child_cases']))
def testParentCase(self): headers = ['parent_id', 'name', 'case_id'] config = self._config(headers, create_new_cases=True, search_column='case_id') rows = 3 parent_case = CommCareCase(domain=self.domain, type=self.default_case_type) parent_case.save() file = MockExcelFile(header_columns=headers, num_rows=rows, row_generator=id_match_generator( parent_case['_id'])) file_missing = MockExcelFile(header_columns=headers, num_rows=rows) # Should successfully match on `rows` cases res = do_import(file, config, self.domain) self.assertEqual(rows, res['created_count']) # Should be unable to find parent case on `rows` cases res = do_import(file_missing, config, self.domain) self.assertEqual( rows, len(res['errors'][ImportErrors.InvalidParentId]['rows']), "All cases should have missing parent")
def _send_case_to_es(self, domain=None, owner_id=None, user_id=None, case_type=None, opened_on=None, closed_on=None): actions = [ CommCareCaseAction( action_type=CASE_ACTION_CREATE, date=opened_on, ) ] case = CommCareCase( _id=uuid.uuid4().hex, domain=domain or self.domain, owner_id=owner_id or self.owner_id, user_id=user_id or self.user_id, type=case_type or self.case_type, opened_on=opened_on or datetime.now(), opened_by=user_id or self.user_id, modified_on=datetime.now(), closed_on=closed_on, closed_by=user_id or self.user_id, actions=actions, ) send_to_elasticsearch('cases', case.to_json()) self.es.indices.refresh(CASE_INDEX_INFO.index) return case
def test_update_dependent_case(self): sync_log = SyncLog( cases_on_phone=[ CaseState( case_id='bran', indices=[ CommCareCaseIndex(identifier='legs', referenced_id='hodor') ], ), ], dependent_cases_on_phone=[CaseState(case_id='hodor')], user_id="someuser") xform_id = uuid.uuid4().hex xform = XFormInstance(_id=xform_id) form_actions = [CommCareCaseAction(action_type=CASE_ACTION_UPDATE, )] with patch.object(CommCareCase, 'get_actions_for_form', return_value=form_actions): parent_case = CommCareCase(_id='hodor') # before this test was added, the following call raised a SyncLogAssertionError on legacy logs. # this test just ensures it doesn't still do that. for log in [ sync_log, SimplifiedSyncLog.from_other_format(sync_log) ]: log.update_phone_lists(xform, [parent_case])
def test_get_list(self): """ Any case in the appropriate domain should be in the list from the API. """ # The actual infrastructure involves saving to CouchDB, having PillowTop # read the changes and write it to ElasticSearch. # the pillow is set to offline mode - elasticsearch not needed to validate fake_case_es = FakeXFormES() v0_3.MOCK_CASE_ES = fake_case_es modify_date = datetime.utcnow() backend_case = CommCareCase(server_modified_on=modify_date, domain=self.domain.name) backend_case.save() self.addCleanup(backend_case.delete) translated_doc = transform_case_for_elasticsearch( backend_case.to_json()) fake_case_es.add_doc(translated_doc['_id'], translated_doc) response = self._assert_auth_get_resource(self.list_endpoint) self.assertEqual(response.status_code, 200) api_cases = json.loads(response.content)['objects'] self.assertEqual(len(api_cases), 1) api_case = api_cases[0] self.assertEqual(api_case['server_date_modified'], json_format_datetime(backend_case.server_modified_on))
class DynamicPropertiesTest(SimpleTestCase): def test_normal(self): case = CommCareCase(foo='some property', bar='some other property') props = case.dynamic_case_properties() self.assertEqual(2, len(props)) self.assertEqual('some property', props['foo']) self.assertEqual('some other property', props['bar'])
def test_get_list(self): """ Any case in the appropriate domain should be in the list from the API. """ # The actual infrastructure involves saving to CouchDB, having PillowTop # read the changes and write it to ElasticSearch. #the pillow is set to offline mode - elasticsearch not needed to validate pillow = CasePillow(online=False) fake_case_es = FakeXFormES() v0_4.MOCK_CASE_ES = fake_case_es modify_date = datetime.utcnow() backend_case = CommCareCase(server_modified_on=modify_date, domain=self.domain.name) backend_case.type = CC_BIHAR_PREGNANCY backend_case.save() translated_doc = pillow.change_transform(backend_case.to_json()) fake_case_es.add_doc(translated_doc['_id'], translated_doc) self.client.login(username=self.username, password=self.password) response = self.client.get(self.list_endpoint) self.assertEqual(response.status_code, 200) api_cases = simplejson.loads(response.content)['objects'] self.assertEqual(len(api_cases), 2) api_case = api_cases['mother_lists'][0] self.assertEqual(dateutil.parser.parse(api_case['server_date_modified']), backend_case.server_modified_on) backend_case.delete()
def test_casedb_already_has_cases(self): casedb_cache = FormProcessorInterface().casedb_cache case = CaseFactory().create_case() case_db = casedb_cache(initial=[CommCareCase(_id='fake1'), CommCareCase(_id='fake2')]) form = XFormInstance.get(case.xform_ids[0]) def assert_exactly_one_case(sender, xform, cases, **kwargs): global case_count case_count = len(cases) cases_received.connect(assert_exactly_one_case) try: process_cases_with_casedb([form], case_db) self.assertEqual(1, case_count) finally: cases_received.disconnect(assert_exactly_one_case)
def test_update_dependent_case_owner_still_present(self): dependent_case_state = CaseState(case_id="d1", indices=[]) sync_log = SyncLog(domain="domain", user_id="user", cases_on_phone=[ CaseState(case_id="c1", indices=[ CommCareCaseIndex( identifier="d1-id", referenced_id="d1") ]) ], dependent_cases_on_phone=[dependent_case_state], owner_ids_on_phone=['user1']) xform_id = uuid.uuid4().hex xform = XFormInstance(_id=xform_id) form_actions = [ CommCareCaseAction(action_type=CASE_ACTION_UPDATE, updated_known_properties={'owner_id': 'user2'}) ] with patch.object(CommCareCase, 'get_actions_for_form', return_value=form_actions): parent_case = CommCareCase(_id='d1') # before this test was added, the following call raised a ValueError on legacy logs. for log in [ sync_log, SimplifiedSyncLog.from_other_format(sync_log) ]: log.update_phone_lists(xform, [parent_case]) self.assertIn(dependent_case_state, log.test_only_get_dependent_cases_on_phone())
def test_update_dependent_case_owner_still_present(self): sync_log = SimplifiedSyncLog( domain="domain", case_ids_on_phone={'c1', 'd1'}, dependent_case_ids_on_phone={'d1'}, index_tree=IndexTree(indices={'c1': { 'd1-id': 'd1' }}), user_id="user", owner_ids_on_phone={'user1'}) dependent_case_state = CaseState(case_id="d1", indices=[]) xform_id = uuid.uuid4().hex xform = XFormInstance(_id=xform_id) form_actions = [ CommCareCaseAction(action_type=CASE_ACTION_UPDATE, updated_known_properties={'owner_id': 'user2'}) ] with patch.object(CommCareCase, 'get_actions_for_form', return_value=form_actions): parent_case = CommCareCase(_id='d1') # before this test was added, the following call raised a ValueError on legacy logs. sync_log.update_phone_lists(xform, [parent_case]) self.assertIn(dependent_case_state, sync_log.test_only_get_dependent_cases_on_phone())
def _test_subtype(self, initial, final): case_id = uuid.uuid4().hex CommCareCase( _id=case_id, domain='fakedomain', ).save() product_id = uuid.uuid4().hex SQLProduct(product_id=product_id, domain='fakedomain').save() report = StockReport.objects.create(form_id=uuid.uuid4().hex, date=ago(1), server_date=datetime.utcnow(), type=const.REPORT_TYPE_BALANCE) txn = StockTransaction( report=report, section_id=const.SECTION_TYPE_STOCK, type=const.TRANSACTION_TYPE_STOCKONHAND, subtype=initial, case_id=case_id, product_id=product_id, stock_on_hand=Decimal(10), ) txn.save() saved = StockTransaction.objects.get(id=txn.id) self.assertEqual(final, saved.subtype)
class TestCheckActionOrder(SimpleTestCase): def test_already_sorted(self): case = CommCareCase(actions=[ CommCareCaseAction(server_date=datetime(2001, 1, 1, 0, 0, 0)), CommCareCaseAction(server_date=datetime(2001, 1, 2, 0, 0, 0)), CommCareCaseAction(server_date=datetime(2001, 1, 3, 0, 0, 0)), ]) self.assertTrue(CouchCaseUpdateStrategy(case).check_action_order())
def setUp(self): self.domain = 'asldkjf-domain' self.case = CommCareCase(domain=self.domain) self.case.save() self.product = make_product(self.domain, 'Product Name', 'prodcode') self._stock_state_key = dict(section_id='stock', case_id=self.case.get_id, product_id=self.product.get_id)
class TestActionSortKey(SimpleTestCase): def test_missing_server_date(self): case = CommCareCase(actions=[ _make_action(server_date=datetime(2001, 1, 1)), _make_action(server_date=None, phone_date=datetime(2001, 1, 1)), ]) with self.assertRaises(MissingServerDate): sorted(case.actions, key=_action_sort_key_function(case))
def setUp(self): self.i1 = CommCareCaseIndex(identifier='i1', referenced_type='t1', referenced_id='id1') self.i2 = CommCareCaseIndex(identifier='i2', referenced_type='t2', referenced_id='id2') self.case = CommCareCase(indices=[self.i1, self.i2])
def get_test_payload(self, domain): from casexml.apps.case.models import CommCareCase return self.get_payload( None, CommCareCase( domain=domain, type='case_type', name='Demo', user_id='user1', prop_a=True, prop_b='value' ) )
def test_load_session_data_for_commconnect_case(self): user = CommCareCase( name='A case', _id=uuid.uuid4().hex ) data = get_user_contributions_to_touchforms_session(user) self.assertEqual('A case', data['username']) self.assertEqual(user._id, data['user_id']) self.assertEqual({}, data['user_data'])
def setUp(self): for doc in XFormInstance.get_db().view('hqadmin/forms_over_time', reduce=False, include_docs=True).all(): #purge all xforms prior to start if doc['doc']['xmlns'] in [ XMLNS_DOTS_FORM, XMLNS_PATIENT_UPDATE_DOT ]: XFormInstance.get_db().delete_doc(doc['doc']) two_weeks = timedelta(days=14) self.domain = Domain() self.domain.name = PACT_DOMAIN self.domain.is_active = True self.domain.date_created = datetime.utcnow() - two_weeks self.domain.save() self.submit_url = '/a/%s/receiver' % self.domain.name self.user = CommCareUser.create(self.domain.name, 'ctsims', 'mockmock', uuid=CTSIMS_ID) nonart_case_regimens = regimen_dict_from_choice( DOT_NONART, "morning,evening,bedtime") art_case_regimens = regimen_dict_from_choice(DOT_ART, "morning,noon") props = { '_id': CASE_ID, 'dot_status': 'DOT1', 'domain': self.domain.name } props.update(nonart_case_regimens) props.update(art_case_regimens) case = CommCareCase(**props) case.save() #generate CaseDoc self.pillbox_form = "" with open( os.path.join(os.path.abspath(os.path.dirname(__file__)), 'dots_data', '01_pillbox.xml')) as fin: self.pillbox_form = fin.read() self.no_pillbox_form = "" with open( os.path.join(os.path.abspath(os.path.dirname(__file__)), 'dots_data', '02_no_pillbox.xml')) as fin: self.no_pillbox_form = fin.read() self.no_pillbox_form2 = "" with open( os.path.join(os.path.abspath(os.path.dirname(__file__)), 'dots_data', '03_no_pillbox.xml')) as fin: self.no_pillbox_form2 = fin.read()
def saving(request): xform = XFormInstance(_attachments={'form.xml': {'data': '-'}}) xform.save() case = CommCareCase() case.save() xform.initial_processing_complete = True xform.save() case.delete() xform.delete() return HttpResponse('Thanks for submitting', status=201)
def setUp(self): for doc in get_all_forms_in_all_domains(): # purge all xforms prior to start if doc.xmlns in [XMLNS_DOTS_FORM, XMLNS_PATIENT_UPDATE_DOT]: doc.delete() two_weeks = timedelta(days=14) self.domain = Domain() self.domain.name = PACT_DOMAIN self.domain.is_active = True self.domain.date_created = datetime.utcnow() - two_weeks self.domain.save() self.submit_url = '/a/%s/receiver' % self.domain.name self.user = CommCareUser.create(self.domain.name, 'ctsims', 'mockmock', None, None, uuid=CTSIMS_ID) nonart_case_regimens = regimen_dict_from_choice( DOT_NONART, "morning,evening,bedtime") art_case_regimens = regimen_dict_from_choice(DOT_ART, "morning,noon") props = { '_id': CASE_ID, 'dot_status': 'DOT1', 'domain': self.domain.name } props.update(nonart_case_regimens) props.update(art_case_regimens) case = CommCareCase(**props) case.save() #generate CaseDoc self.pillbox_form = "" with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'dots_data', '01_pillbox.xml'), encoding='utf-8') as fin: self.pillbox_form = fin.read() self.no_pillbox_form = "" with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'dots_data', '02_no_pillbox.xml'), encoding='utf-8') as fin: self.no_pillbox_form = fin.read() self.no_pillbox_form2 = "" with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'dots_data', '03_no_pillbox.xml'), encoding='utf-8') as fin: self.no_pillbox_form2 = fin.read()
def setUp(self): super(TestReverseIndexedCases, self).setUp() self.domain = 'domain' self.factory = CaseFactory(self.domain) self.indexed_case_id = uuid.uuid4().hex self.index = CommCareCaseIndex(identifier="host", referenced_type="host", relationship=CASE_INDEX_EXTENSION, referenced_id=self.indexed_case_id) self.case = CommCareCase(domain=self.domain, indices=[self.index]) self.case.save()
def setUpClass(cls): cls.domain = Domain(name='test') cls.domain.save() cls.case_id = uuid.uuid4().hex CommCareCase( _id=cls.case_id, domain='fakedomain', ).save() cls.product_id = uuid.uuid4().hex SQLProduct(product_id=cls.product_id).save()