<commit_before>from __future__ import absolute_import
from datetime import datetime
import pytz
import os
import mock
from django.test import TestCase, override_settings


from corehq.form_processor.tests.utils import FormProcessorTestUtils

from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
from custom.enikshay.integrations.ninetyninedots.views import (
    validate_adherence_values,
    validate_beneficiary_id,
)
from custom.enikshay.case_utils import get_open_episode_case_from_person
from custom.enikshay.integrations.ninetyninedots.api_spec import load_api_spec
from custom.enikshay.integrations.ninetyninedots.utils import (
    create_adherence_cases,
    PatientDetailsUpdater,
    update_adherence_confidence_level,
    update_default_confidence_level,
)
from custom.enikshay.integrations.ninetyninedots.exceptions import NinetyNineDotsException
from custom.enikshay.tests.utils import ENikshayCaseStructureMixin


def property_setter(param, val, sector):
    return {'property_set_with_setter': val}


@override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True)
class Receiver99DotsTests(ENikshayCaseStructureMixin, TestCase):
    def setUp(self):
        super(Receiver99DotsTests, self).setUp()
        self.fake_api_spec_patch = mock.patch('custom.enikshay.integrations.ninetyninedots.utils.load_api_spec')
        fake_api_spec = self.fake_api_spec_patch.start()
        fake_api_spec.return_value = load_api_spec(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_api_spec.yaml')
        )
        self.spec = fake_api_spec()
        self.create_case_structure()

    def tearDown(self):
        self.fake_api_spec_patch.stop()

    def _get_fake_request(self):
        fake_request = {prop: '123' for prop in self.spec.required_params}
        fake_request['beneficiary_id'] = self.person_id
        return fake_request

    def test_required_properties(self):
        # request with required properties gets passed through fine
        PatientDetailsUpdater(self.domain, self._get_fake_request())

        # Without the required property, raises an error
        with self.assertRaises(NinetyNineDotsException) as e:
            PatientDetailsUpdater(None, {'boop': 'barp'})
        self.assertTrue(", ".join(self.spec.required_params) in str(e.exception))

    def test_patient_not_found(self):
        fake_request = self._get_fake_request()
        fake_request['beneficiary_id'] = '123'
        with self.assertRaises(NinetyNineDotsException) as e:
            PatientDetailsUpdater(None, fake_request)
        self.assertTrue(str(e.exception), "No patient exists with this beneficiary ID")

    def test_invalid_choice(self):
        fake_request = self._get_fake_request()

        # A request with a valid choice passes through fine
        fake_request['has_choices'] = 'foo'
        PatientDetailsUpdater(None, fake_request)

        # A request with an invalid choice raises an error
        fake_request = self._get_fake_request()
        fake_request['has_choices'] = 'biff'
        with self.assertRaises(NinetyNineDotsException) as e:
            PatientDetailsUpdater(None, fake_request)
        self.assertEqual(str(e.exception), "biff is not a valid value for has_choices.")

    def test_wrong_direction(self):
        fake_request = self._get_fake_request()
        fake_request['outbound_only'] = 'foo'
        with self.assertRaises(NinetyNineDotsException) as e:
            PatientDetailsUpdater(self.domain, fake_request).update_cases()
        self.assertEqual(str(e.exception), "outbound_only is not a valid parameter to update")

        fake_request = self._get_fake_request()
        fake_request['inbound_only'] = 'bar'
        # shouldn't throw an exception
        PatientDetailsUpdater(self.domain, fake_request).update_cases()

    def test_update_with_setter(self):
        fake_request = self._get_fake_request()
        fake_request['with_setter'] = 'foo'

        PatientDetailsUpdater(self.domain, fake_request).update_cases()

        person_case = CaseAccessors(self.domain).get_case(self.person_id)
        self.assertEqual(person_case.get_case_property('property_set_with_setter'), 'foo')

    def test_case_update(self):
        fake_request = self._get_fake_request()
        fake_request['has_choices'] = 'foo'
        PatientDetailsUpdater(self.domain, fake_request).update_cases()

        person_case = CaseAccessors(self.domain).get_case(self.person_id)
        self.assertEqual(person_case.get_case_property('required_param'), '123')

        episode_case = CaseAccessors(self.domain).get_case(self.episode_id)
        self.assertEqual(episode_case.get_case_property('has_choices'), 'foo')

    def test_split_name(self):
        fake_request = self._get_fake_request()

        fake_request['split_name'] = '<NAME>face Stark'
        PatientDetailsUpdater(self.domain, fake_request).update_cases()

        person_case = CaseAccessors(self.domain).get_case(self.person_id)
        self.assertEqual(person_case.get_case_property('foo'), 'Arya')
        self.assertEqual(person_case.get_case_property('bar'), 'Horseface Stark')

    def test_unwrap_number(self):
        fake_request = self._get_fake_request()

        fake_request['unwrap_number'] = '+91123456789'
        PatientDetailsUpdater(self.domain, fake_request).update_cases()

        person_case = CaseAccessors(self.domain).get_case(self.person_id)
        self.assertEqual(person_case.get_case_property('foo'), '91123456789')

    def test_private_only(self):
        fake_request = self._get_fake_request()

        fake_request['private_only'] = 'so private'
        with self.assertRaises(NinetyNineDotsException) as e:
            PatientDetailsUpdater(self.domain, fake_request).update_cases()

    def test_merm_params(self):
        fake_request = self._get_fake_request()

        fake_request['merm_params'] = {
            "IMEI": "1321",
            "daily_reminder_status": "1",
            "daily_reminder_time": "12:00",
            "refill_reminder_status": "1",
            "refill_reminder_datetime": "2017/12/12 15:54:00",
            "RT_hours": "1",
        }
        PatientDetailsUpdater(self.domain, fake_request).update_cases()
        person_case = CaseAccessors(self.domain).get_case(self.episode_id)
        self.assertEqual(person_case.get_case_property('merm_id'), '1321')

    def test_validate_patient_adherence_data(self):
        with self.assertRaises(NinetyNineDotsException) as e:<commit_msg>lint [ci skip]<commit_after>from __future__ import absolute_import
from datetime import datetime
import pytz
import os
import mock
from django.test import TestCase, override_settings


from corehq.form_processor.tests.utils import FormProcessorTestUtils

from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
from custom.enikshay.integrations.ninetyninedots.views import (
    validate_adherence_values,
    validate_beneficiary_id,
)
from custom.enikshay.case_utils import get_open_episode_case_from_person
from custom.enikshay.integrations.ninetyninedots.api_spec import load_api_spec
from custom.enikshay.integrations.ninetyninedots.utils import (
    create_adherence_cases,
    PatientDetailsUpdater,
    update_adherence_confidence_level,
    update_default_confidence_level,
)
from custom.enikshay.integrations.ninetyninedots.exceptions import NinetyNineDotsException
from custom.enikshay.tests.utils import ENikshayCaseStructureMixin


def property_setter(param, val, sector):
    return {'property_set_with_setter': val}


@override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True)
class Receiver99DotsTests(ENikshayCaseStructureMixin, TestCase):
    def setUp(self):
        super(Receiver99DotsTests, self).setUp()
        self.fake_api_spec_patch = mock.patch('custom.enikshay.integrations.ninetyninedots.utils.load_api_spec')
        fake_api_spec = self.fake_api_spec_patch.start()
        fake_api_spec.return_value = load_api_spec(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_api_spec.yaml')
        )
        self.spec = fake_api_spec()
        self.create_case_structure()

    def tearDown(self):
        self.fake_api_spec_patch.stop()

    def _get_fake_request(self):
        fake_request = {prop: '123' for prop in self.spec.required_params}
        fake_request['beneficiary_id'] = self.person_id
        return fake_request

    def test_required_properties(self):
        # request with required properties gets passed through fine
        PatientDetailsUpdater(self.domain, self._get_fake_request())

        # Without the required property, raises an error
        with self.assertRaises(NinetyNineDotsException) as e:
            PatientDetailsUpdater(None, {'boop': 'barp'})
        self.assertTrue(", ".join(self.spec.required_params) in str(e.exception))

    def test_patient_not_found(self):
        fake_request = self._get_fake_request()
        fake_request['beneficiary_id'] = '123'
        with self.assertRaises(NinetyNineDotsException) as e:
            PatientDetailsUpdater(None, fake_request)
        self.assertTrue(str(e.exception), "No patient exists with this beneficiary ID")

    def test_invalid_choice(self):
        fake_request = self._get_fake_request()

        # A request with a valid choice passes through fine
        fake_request['has_choices'] = 'foo'
        PatientDetailsUpdater(None, fake_request)

        # A request with an invalid choice raises an error
        fake_request = self._get_fake_request()
        fake_request['has_choices'] = 'biff'
        with self.assertRaises(NinetyNineDotsException) as e:
            PatientDetailsUpdater(None, fake_request)
        self.assertEqual(str(e.exception), "biff is not a valid value for has_choices.")

    def test_wrong_direction(self):
        fake_request = self._get_fake_request()
        fake_request['outbound_only'] = 'foo'
        with self.assertRaises(NinetyNineDotsException) as e:
            PatientDetailsUpdater(self.domain, fake_request).update_cases()
        self.assertEqual(str(e.exception), "outbound_only is not a valid parameter to update")

        fake_request = self._get_fake_request()
        fake_request['inbound_only'] = 'bar'
        # shouldn't throw an exception
        PatientDetailsUpdater(self.domain, fake_request).update_cases()

    def test_update_with_setter(self):
        fake_request = self._get_fake_request()
        fake_request['with_setter'] = 'foo'

        PatientDetailsUpdater(self.domain, fake_request).update_cases()

        person_case = CaseAccessors(self.domain).get_case(self.person_id)
        self.assertEqual(person_case.get_case_property('property_set_with_setter'), 'foo')

    def test_case_update(self):
        fake_request = self._get_fake_request()
        fake_request['has_choices'] = 'foo'
        PatientDetailsUpdater(self.domain, fake_request).update_cases()

        person_case = CaseAccessors(self.domain).get_case(self.person_id)
        self.assertEqual(person_case.get_case_property('required_param'), '123')

        episode_case = CaseAccessors(self.domain).get_case(self.episode_id)
        self.assertEqual(episode_case.get_case_property('has_choices'), 'foo')

    def test_split_name(self):
        fake_request = self._get_fake_request()

        fake_request['split_name'] = '<NAME>'
        PatientDetailsUpdater(self.domain, fake_request).update_cases()

        person_case = CaseAccessors(self.domain).get_case(self.person_id)
        self.assertEqual(person_case.get_case_property('foo'), 'Arya')
        self.assertEqual(person_case.get_case_property('bar'), 'Horseface Stark')

    def test_unwrap_number(self):
        fake_request = self._get_fake_request()

        fake_request['unwrap_number'] = '+91123456789'
        PatientDetailsUpdater(self.domain, fake_request).update_cases()

        person_case = CaseAccessors(self.domain).get_case(self.person_id)
        self.assertEqual(person_case.get_case_property('foo'), '91123456789')

    def test_private_only(self):
        fake_request = self._get_fake_request()

        fake_request['private_only'] = 'so private'
        with self.assertRaises(NinetyNineDotsException):
            PatientDetailsUpdater(self.domain, fake_request).update_cases()

    def test_merm_params(self):
        fake_request = self._get_fake_request()

        fake_request['merm_params'] = {
            "IMEI": "1321",
            "daily_reminder_status": "1",
            "daily_reminder_time": "12:00",
            "refill_reminder_status": "1",
            "refill_reminder_datetime": "2017/12/12 15:54:00",
            "RT_hours": "1",
        }
        PatientDetailsUpdater(self.domain, fake_request).update_cases()
        person_case = CaseAccessors(self.domain).get_case(self.episode_id)
        self.assertEqual(person_case.get_case_property('merm_id'), '1321')

    def test_validate_patient_adherence_data(self):
        with self.assertRaises(NinetyNineDotsException) as e:
{'fraction_non_alphanumeric': 0.09481299061105125, 'fraction_numerical': 0.009850700323226104, 'mean_word_length': 3.9111866969009825, 'pattern_counts': {'":': 12, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5013109', 'n_tokens_mistral': 4139, 'n_tokens_neox': 3939, 'n_words': 642}