예제 #1
0
    def test_post_customer_creation_first_method(self, mock_post):
        expected_body = {
            'base': {
                'contacts': {
                    'email': '*****@*****.**'
                }
            },
            'extra': 'extra',
            'extended': {
                'prova': 'prova'
            },
            'tags': {
                'auto': ['auto'],
                'manual': ['manual']
            }
        }
        mock_post.return_value = json.loads(
            FakeHTTPResponse(resp_path='tests/util/fake_post_response').text)
        c = Customer(
            node=self.node,
            base=Properties(contacts=Properties(email='*****@*****.**')))

        c.extra = 'extra'
        c.extended.prova = 'prova'
        c.tags.auto = ['auto']
        c.tags.manual = ['manual']

        c.post()
        mock_post.assert_called_with(body=expected_body, force_update=False)
    def test_query(self, mock_get):
        mock_get.return_value = FakeHTTPResponse(
            resp_path='tests/util/fake_query_response')
        query_expected = {
            'name': 'query',
            'query': {
                'type': 'simple',
                'name': 'query',
                'are': {
                    'condition': {
                        'type':
                        'composite',
                        'conditions': [{
                            'type': 'atomic',
                            'attribute': 'base.contacts.email',
                            'operator': 'EQUALS',
                            'value': '*****@*****.**'
                        }, {
                            'type': 'atomic',
                            'attribute': 'extra',
                            'operator': 'EQUALS',
                            'value': 'Ciao'
                        }],
                        'conjunction':
                        'and'
                    }
                }
            }
        }

        customers_query = self.node.query(Customer).filter(
            (Customer.base.contacts.email == '*****@*****.**')
            & (Customer.extra == 'Ciao')).all()
        params_expected = {
            'nodeId': '123',
            'query': json.dumps(query_expected)
        }
        base_url = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'

        mock_get.assert_called_with(base_url,
                                    params=params_expected,
                                    headers=self.headers_expected)

        assert customers_query[
            0].base.contacts.email == '*****@*****.**', customers_query[
                0].base.contacts.email
        assert customers_query[0].extra == 'Ciao', customers_query[0].extra
class TestEvent(unittest.TestCase):
    @classmethod
    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_event_response'))
    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def setUp(cls, mock_get_customers, mock_get_events):
        w = Workspace(workspace_id="123", token="456")
        cls.node = w.get_node("123")
        cls.customer = cls.node.get_customers()[0]
        cls.events = cls.customer.get_events()
        cls.base_url = 'https://api.contactlab.it/hub/v1/workspaces/123/events'
        cls.headers_expected = {
            'Authorization': 'Bearer 456',
            'Content-Type': 'application/json'
        }

    @classmethod
    def tearDown(cls):
        pass

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_event_response'))
    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_get_event_from_customers(self, mock_get_customers,
                                      mock_get_events):
        events = self.node.get_customers()[0].get_events()
        assert isinstance(events, PaginatedList), type(events)
        assert isinstance(events[0], Event), type(events[0])
        try:
            events.append(Event(node=self.node))
        except ValueError as e:
            assert 'Read Only' in str(e)

    def test_get_properties(self):
        prop = self.events[0].properties
        assert isinstance(prop, Properties), type(prop)

    def test_get_unexsistent(self):
        try:
            prop = self.events[0].attr
        except AttributeError as e:
            assert 'attr' in str(e), str(e)

    def test_create_new_event_properties(self):
        e = Event(node=self.node)
        e.properties = Properties(attr='attr')
        assert isinstance(e.properties, Properties), type(e.properties)

    def test_set_event_properties(self):
        e = self.events[0]
        assert isinstance(e.properties, Properties)
        e.context = Event.CONTEXTS.DIGITAL_CAMPAIGN
        assert e.context == Event.CONTEXTS.DIGITAL_CAMPAIGN, e.context

    def test_event_from_dict_void(self):
        e = Event.from_dict(node=self.node)
        assert e.attributes == {}, e.attributes

    def test_event_from_dict(self):
        d = {}
        e = Event.from_dict(node=self.node, attributes=d)
        assert e.attributes is d, (e.attributes, d)

    def test_to_dict(self):
        e = Event(
            node=self.node,
            a=Properties(b=Properties(c=Properties(d=Properties(e='f')))))
        assert e.to_dict() == {
            'a': {
                'b': {
                    'c': {
                        'd': {
                            'e': 'f'
                        }
                    }
                }
            }
        }, e.to_dict()

    def test_list_properies(self):
        e = Event(node=self.node)
        e.a = [Properties(a='b')]
        assert e.attributes == {'a': [{'a': 'b'}]}, e.attributes

    def test_list_properies_constructor(self):
        e = Event(node=self.node, a=[Properties(a='b')])
        assert e.attributes == {'a': [{'a': 'b'}]}, e.attributes

    @mock.patch('requests.post',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_event_response'))
    def test_post(self, mock_post):
        e = Event(node=self.node,
                  a=[Properties(a='b')],
                  b='c',
                  d=Properties(f='g', h=Properties(i='j')),
                  k=dict(l=Properties(m='n', o='p')))
        e.post()
        mock_post.assert_called_with(self.base_url,
                                     headers=self.headers_expected,
                                     json={
                                         'a': [{
                                             'a': 'b'
                                         }],
                                         'b': 'c',
                                         'd': {
                                             'f': 'g',
                                             'h': {
                                                 'i': 'j'
                                             }
                                         },
                                         'k': {
                                             'l': {
                                                 'm': 'n',
                                                 'o': 'p'
                                             }
                                         }
                                     })

    @mock.patch('requests.post',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_event_response'))
    def test_post_bring_back(self, mock_post):
        e = Event(node=self.node,
                  a=[Properties(a='b')],
                  b='c',
                  bringBackProperties=Properties(type='EXTERNAL_ID',
                                                 value='01'),
                  d=Properties(f='g', h=Properties(i='j')),
                  k=dict(l=Properties(m='n', o='p')))
        e.post()
        mock_post.assert_called_with(self.base_url,
                                     headers=self.headers_expected,
                                     json={
                                         'bringBackProperties': {
                                             'type': 'EXTERNAL_ID',
                                             'value': '01',
                                             'nodeId': self.node.node_id
                                         },
                                         'a': [{
                                             'a': 'b'
                                         }],
                                         'b': 'c',
                                         'd': {
                                             'f': 'g',
                                             'h': {
                                                 'i': 'j'
                                             }
                                         },
                                         'k': {
                                             'l': {
                                                 'm': 'n',
                                                 'o': 'p'
                                             }
                                         }
                                     })
예제 #4
0
class TestJob(unittest.TestCase):

    @classmethod
    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def setUp(cls, mock_get_customers):
        w = Workspace(workspace_id="123", token="456")
        cls.node = w.get_node("123")
        cls.customers = cls.node.get_customers()
        cls.headers_expected = {'Authorization': 'Bearer 456', 'Content-Type': 'application/json'}
        cls.base_url_customer = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'
        cls.customer = Customer(id='01', node=cls.node)
        cls.job = Job(customer=cls.customer, **{'id': '01'})

    @classmethod
    def tearDown(cls):
        pass

    def test_from_dict_no_attr(self):
        e = Job.from_dict(customer=self.customer)
        assert e.attributes == {}, e.attributes

    def test_set_job(self):
        self.job.jobTitle = "title"
        assert self.job.jobTitle == "title", self.job.jobTitle

    def test_set_job_customer(self):
        self.customers[0].base.jobs[0].jobTitle = "title"
        self.customers[0].base.jobs[0].endDate = u'1994-10-06'

        edu = self.customers[0].base.jobs[0]
        edu.isCurrent = False

        mute = {'base.jobs':
                             [{u'companyIndustry': u'companyIndustry',
                               u'companyName': u'companyName',
                               u'startDate': u'1994-10-06',
                               u'endDate': u'1994-10-06',
                               u'jobTitle': u'title',
                               u'isCurrent': False}]}
        mute_res = {'base': {'jobs':
                             [{u'companyIndustry': u'companyIndustry',
                               u'companyName': u'companyName',
                               u'startDate': u'1994-10-06',
                               u'endDate': u'1994-10-06',
                               u'jobTitle': u'title',
                               u'isCurrent': False}]}}
        assert self.customers[0].mute == mute, self.customers[0].mute
        res = resolve_mutation_tracker(self.customers[0].mute)
        assert res == mute_res, res

    def test_set_job_customer_add(self):
        self.customers[0].base.jobs[0].isCurrent = False
        self.customers[0].base.jobs += [Job(customer=self.customers[0], id='01')]

        mute = {'base.jobs': [
            {u'companyIndustry': u'companyIndustry',
             u'companyName': u'companyName',
             u'startDate': u'1994-10-06',
             u'endDate': u'1994-10-06',
             u'jobTitle': u'jobTitle',
             u'isCurrent': False},
            {u'id': u'01'}
        ]
        }
        mute_res = {'base': {'jobs': [
            {u'companyIndustry': u'companyIndustry',
             u'companyName': u'companyName',
             u'startDate': u'1994-10-06',
             u'endDate': u'1994-10-06',
             u'jobTitle': u'jobTitle',
             u'isCurrent': False},
            {u'id': u'01'}
        ]
        }
        }
        assert self.customers[0].mute == mute, self.customers[0].mute
        res = resolve_mutation_tracker(self.customers[0].mute)
        assert res == mute_res, res

    @mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_job_response'))
    def test_post_job(self, mock_post):
        j = Job(customer=self.customer, id='01', companyIndustry='companyIndustry', startDate=u'1994-10-06',
                endDate=u'1994-10-06', companyName='companyName', jobTitle='jobTitle',
                isCurrent=True)
        j.post()

        mock_post.assert_called_with(self.base_url_customer + '/' + self.customer.id + '/jobs',
                                    headers=self.headers_expected,
                                    json=j.attributes)
        assert self.customer.base.jobs[0].attributes == j.attributes, (self.customer.base.jobs[0].attributes
                                                                       ,j.attributes)

    @mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_job_response'))
    def test_post_job_create_base(self, mock_post):
        c = Customer(node=self.node, default_attributes={}, id='01')
        j = Job(customer=c, id='01', companyIndustry='companyIndustry', startDate=u'1994-10-06',
                endDate=u'1994-10-06', companyName='companyName', jobTitle='jobTitle',
                isCurrent=True)
        j.post()

        mock_post.assert_called_with(self.base_url_customer + '/' + c.id + '/jobs',
                                    headers=self.headers_expected,
                                    json=j.attributes)
        assert c.base.jobs[0].attributes == j.attributes, (c.base.jobs[0].attributes, j.attributes)

    @mock.patch('requests.delete', return_value=FakeHTTPResponse(resp_path='tests/util/fake_job_response'))
    def test_delete(self, mock_post):
        j = Job(customer=self.customer, id='01')
        j.delete()
        mock_post.assert_called_with(self.base_url_customer + '/' + self.customer.id + '/jobs/01',
                                    headers=self.headers_expected)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_job_response'))
    def test_put(self, mock_post):
        self.customer.base.jobs = [self.job]
        self.job.companyIndustry= 'companyIndustry'
        self.job.companyName = 'companyName'
        self.job.jobTitle = 'jobTitle'
        self.job.startDate = '1994-10-06'
        self.job.endDate = '1994-10-06'
        self.job.isCurrent = True

        self.job.put()
        mock_post.assert_called_with(self.base_url_customer + '/' + self.customer.id + '/jobs/01',
                                    headers=self.headers_expected, json=self.job.attributes)
        assert self.customer.base.jobs[0].attributes == self.job.attributes,  (self.customer.base.jobs[0].attributes,
                                                                               self.job.attributes)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_put_no_jobs(self, mock_post):
        self.job.companyIndustry= 'companyIndustry'
        self.job.companyName = 'companyName'
        self.job.jobTitle = 'jobTitle'
        self.job.startDate = '1994-10-06'
        self.job.endDate = '1994-10-06'
        self.job.isCurrent = True
        try:
            self.job.put()
        except ValueError as e:
            assert 'Job' in str(e)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_put_no_job(self, mock_post):
        self.customer.base.jobs = [self.job]
        job = Job(customer=self.customer, id='03')
        job.companyIndustry = 'companyIndustry'
        job.companyName = 'companyName'
        job.jobTitle = 'jobTitle'
        job.startDate = '1994-10-06'
        job.endDate = '1994-10-06'
        job.isCurrent = True
        try:
            job.put()
        except ValueError as e:
            assert 'Job' in str(e)

    def test_create_job_new_c(self):
        j = Job(customer=Customer(node=self.node), a='b')
        try:
            j.post()
        except AttributeError as e:
            assert "Customer object has no attribute 'id'" in str(e), str(e)
예제 #5
0
class TestLike(unittest.TestCase):

    @classmethod
    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def setUp(cls, mock_get_customers):
        w = Workspace(workspace_id="123", token="456")
        cls.node = w.get_node("123")
        cls.customers = cls.node.get_customers()
        cls.headers_expected = {'Authorization': 'Bearer 456', 'Content-Type': 'application/json'}
        cls.base_url_customer = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'
        cls.customer = Customer(id='01', node=cls.node)
        cls.like = Like(customer=cls.customer, **{'id': 'id'})

    @classmethod
    def tearDown(cls):
        pass

    def test_from_dict_no_attr(self):
        e = Like.from_dict(customer=self.customer)
        assert e.attributes == {}, e.attributes

    def test_set_like(self):
        self.like.name = "name"
        assert self.like.name == "name", self.like.name

    def test_set_like_customer(self):
        self.customers[0].base.likes[0].name = 'name1'
        self.customers[0].base.likes[0].category = 'category1'

        like = self.customers[0].base.likes[0]

        mute = {'base.likes':
                             [{'name':'name1',
                               'category':'category1',
                               'id':'id',
                               'createdTime':'1994-02-11 14:05'}]}
        mute_res= {'base': {'likes':
                             [{'name':'name1',
                               'category':'category1',
                               'id':'id',
                               'createdTime':'1994-02-11 14:05'}]}}
        assert self.customers[0].mute == mute, self.customers[0].mute
        res = resolve_mutation_tracker(self.customers[0].mute)
        assert res == mute_res, res

    def test_set_like_customer_add(self):
        self.customers[0].base.likes[0].name = 'name1'
        self.customers[0].base.likes += [Like(customer=self.customers[0], id='01')]

        mute_res = {'base': {'likes': [
            {'name': 'name1',
             'category': 'category',
             'id': 'id',
             'createdTime': '1994-02-11 14:05'},
            {u'id': u'01'}
        ]
        }
        }
        mute = {'base.likes': [
            {'name': 'name1',
             'category': 'category',
             'id': 'id',
             'createdTime': '1994-02-11 14:05'},
            {u'id': u'01'}
        ]
        }

        assert self.customers[0].mute == mute, self.customers[0].mute
        res = resolve_mutation_tracker(self.customers[0].mute)
        assert res == mute_res, res


    @mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_like_response'))
    def test_post_like(self, mock_post):
        j = Like(customer=self.customer, id='id', category='category', name='name', createdTime='1994-02-11T14:05M')
        j.post()

        mock_post.assert_called_with(self.base_url_customer +'/' + self.customer.id + '/likes',
                                    headers=self.headers_expected,
                                    json=j.attributes)
        assert self.customer.base.likes[0].attributes == j.attributes, (self.customer.base.likes[0].attributes
                                                                       ,j.attributes)

    @mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_like_response'))
    def test_post_like_create_base(self, mock_post):
        c = Customer(node=self.node, default_attributes={}, id='01')
        j = Like(customer=c, id='id', category='category', name='name', createdTime='1994-02-11T14:05M')
        j.post()

        mock_post.assert_called_with(self.base_url_customer +'/' + c.id + '/likes',
                                    headers=self.headers_expected,
                                     json=j.attributes)
        assert c.base.likes[0].attributes == j.attributes, (c.base.likes[0].attributes, j.attributes)

    @mock.patch('requests.delete', return_value=FakeHTTPResponse(resp_path='tests/util/fake_like_response'))
    def test_delete(self, mock_post):
        j = Like(customer=self.customer, id='id')
        j.delete()
        mock_post.assert_called_with(self.base_url_customer +'/' +self.customer.id + '/likes/id',
                                    headers=self.headers_expected)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_like_response'))
    def test_put(self, mock_post):
        self.customer.base.likes = [self.like]
        self.like.name = 'name'
        self.like.category = 'category'
        self.like.createdTime = '1994-02-11T14:05M'

        self.like.put()
        mock_post.assert_called_with(self.base_url_customer +'/' + self.customer.id + '/likes/id',
                                    headers=self.headers_expected, json=self.like.attributes)
        assert self.customer.base.likes[0].attributes == self.like.attributes,  (self.customer.base.likes[0].attributes,
                                                                               self.like.attributes)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_put_no_likes(self, mock_post):
        self.like.name = 'name'
        self.like.category = 'category'
        self.like.cratedTime = '1994-02-11T14:05M'
        try:
            self.like.put()
        except ValueError as e:
            assert 'Like' in str(e)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_put_no_like(self, mock_post):
        self.customer.base.likes = [self.like]
        like = Like(customer=self.customer, id='03')
        like.name = 'name'
        like.category = 'category'
        like.cratedTime = '1994-02-11T14:05M'
        try:
            like.put()
        except ValueError as e:
            assert 'Like' in str(e)
예제 #6
0
class TestEducation(unittest.TestCase):
    @classmethod
    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def setUp(cls, mock_get_customers):
        w = Workspace(workspace_id="123", token="456")
        cls.node = w.get_node("123")
        cls.customers = cls.node.get_customers()
        cls.headers_expected = {'Authorization': 'Bearer 456', 'Content-Type': 'application/json'}
        cls.base_url_customer = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'
        cls.customer = Customer(id='01', node=cls.node)
        cls.education = Education(customer=cls.customer, **{'id': '01'})

    @classmethod
    def tearDown(cls):
        pass

    def test_from_dict_no_attr(self):
        e = Education.from_dict(customer=self.customer)
        assert e.attributes == {}, e.attributes

    def test_set_education(self):
        self.education.schoolType = Education.SCHOOL_TYPES.COLLEGE
        assert self.education.schoolType == Education.SCHOOL_TYPES.COLLEGE, self.education.schoolType

    def test_set_education_customer(self):
        self.customers[0].base.educations[0].schoolType = Education.SCHOOL_TYPES.SECONDARY_SCHOOL
        self.customers[0].base.educations[0].startYear = 1992

        edu = self.customers[0].base.educations[0]
        edu.isCurrent = False

        mute = {'base.educations':
                             [{u'schoolType': 'SECONDARY_SCHOOL',
                               u'startYear': 1992,
                               u'schoolName': u'schoolName',
                               u'schoolConcentration': u'schoolConcentration',
                               u'endYear': 2000,
                               u'isCurrent': False}]}
        assert self.customers[0].mute == mute, self.customers[0].mute

    def test_set_education_customer_add(self):
        self.customers[0].base.educations[0].isCurrent = False
        self.customers[0].base.educations += [Education(customer=self.customers[0], id='01')]

        mute = {'base.educations': [
            {u'schoolType': 'COLLEGE',
             u'startYear': 1994,
             u'schoolName': u'schoolName',
             u'schoolConcentration': u'schoolConcentration',
             u'endYear': 2000,
             u'isCurrent': False},
            {u'id': u'01'}
        ]
        }

        assert self.customers[0].mute == mute, self.customers[0].mute

    @mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_post_education(self, mock_post):
        e = Education(customer=self.customer, id='01', schoolType='COLLEGE', startYear=1994, endYear=2000,
                      schoolName='schoolName', schoolConcentration='schoolConcentration', isCurrent=True)
        e.post()

        mock_post.asser_called_with(self.base_url_customer + '/' + self.customer.id +'/educations',
                                    headers=self.headers_expected,
                                    json=e.attributes)
        assert self.customer.base.educations[0].attributes == e.attributes, self.customer.attributes

    @mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_post_education_create_base(self, mock_post):
        c = Customer(node=self.node, default_attributes={}, id='01')
        e = Education(customer=c, id='01', schoolType='COLLEGE', startYear=1994, endYear=2000,
                      schoolName='schoolName', schoolConcentration='schoolConcentration', isCurrent=True)

        e.post()

        mock_post.assert_called_with(self.base_url_customer + '/' + c.id + '/educations',
                                    headers=self.headers_expected,
                                    json=e.attributes)
        assert c.base.educations[0].attributes == e.attributes, c.customer.attributes

    @mock.patch('requests.delete', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_delete(self, mock_post):
        e = Education(customer=self.customer, id='01')
        e.delete()
        mock_post.assert_called_with(self.base_url_customer + '/' + self.customer.id + '/educations/01',
                                    headers=self.headers_expected)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_put(self, mock_post):
        self.customer.base.educations = [self.education]
        self.education.schoolType= 'COLLEGE'
        self.education.startYear = 1994
        self.education.endYear = 2000
        self.education.schoolConcentration = 'schoolConcentration'
        self.education.schoolName = 'schoolName'
        self.education.isCurrent = True

        self.education.put()
        mock_post.assert_called_with(self.base_url_customer + '/' + self.customer.id + '/educations/01',
                                    headers=self.headers_expected, json=self.education.attributes)
        assert self.customer.base.educations[0].attributes == self.education.attributes,  self.customer.base.educations[0].attributes

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_put_no_educations(self, mock_post):
        self.education.schoolType = 'COLLEGE'
        self.education.startYear = 1994
        self.education.endYear = 2000
        self.education.schoolConcentration = 'schoolConcentration'
        self.education.schoolName = 'schoolName'
        self.education.isCurrent = True
        try:
            self.education.put()
        except ValueError as e:
            assert 'Education' in str(e)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_put_no_education(self, mock_post):
        self.customer.base.educations = [self.education]
        education = Education(customer=self.customer, id='03')
        education.schoolType = 'COLLEGE'
        education.startYear = 1994
        education.endYear = 2000
        education.schoolConcentration = 'schoolConcentration'
        education.schoolName = 'schoolName'
        education.isCurrent = True
        try:
            education.put()
        except ValueError as e:
            assert 'Education' in str(e)
예제 #7
0
class TestWorkspace(TestSuite):
    @classmethod
    def setUp(cls):
        cls.workspace_id = '123'
        cls.node_id = '456'
        cls.token = 'abc'

    @classmethod
    def tearDown(cls):
        pass

    def test_workspace_from_ini_file(self):
        w = Workspace.from_ini_file('tests/util/config.ini')
        assert w.workspace_id == str(123), w.workspace_id
        assert w.token == str(456), w.token

    def test_workspace_from_incorrect_ini_file(self):
        try:
            w = Workspace.from_ini_file('tests/util/wrong_config.ini')
        except KeyError as e:
            assert e.args[
                0] == 'workspace_id or token parameter not found in INI file', e.message

    def test_workspace_from_unexistent_ini_file(self):
        try:
            w = Workspace.from_ini_file('file')
        except IOError as e:
            assert 'No such file or directory' == e.args[1], e.args[1]

    def test_workspace_from_ini_file_base_url(self):
        w = Workspace.from_ini_file('tests/util/config_base.ini')
        assert w.workspace_id == str(123), w.workspace_id
        assert w.token == str(456), w.token
        assert w.base_url == 'http', w.base_url

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_get_node(self, mock_get):
        w = Workspace(workspace_id=self.workspace_id, token=self.token)
        n = w.get_node(self.node_id).get_customers()
        node_in_req = mock_get.call_args[1]['params']['nodeId']
        assert node_in_req == self.node_id, node_in_req

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_get_node_with_int_param(self, mock_get):
        w = Workspace(workspace_id=self.workspace_id, token=self.token)
        n = w.get_node(1).get_customers()
        assert mock_get.call_args[1]['params'][
            'nodeId'] == '1', mock_get.call_args[1]['params']['nodeId']

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_workspace(self, mock_get):
        w = Workspace(workspace_id=self.workspace_id, token=self.token)
        n = w.get_node(self.node_id).get_customers()
        authorization = mock_get.call_args[1]['headers']['Authorization']
        request_url = mock_get.call_args[0][0]
        assert authorization == 'Bearer ' + self.token, authorization
        assert self.workspace_id in request_url, request_url

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_workspace_with_int_params(self, mock_get):
        w = Workspace(workspace_id=1, token=2)
        n = w.get_node(3).get_customers()
        authorization = mock_get.call_args[1]['headers']['Authorization']
        request_url = mock_get.call_args[0][0]
        assert authorization == 'Bearer 2', authorization
        assert '1' in request_url, request_url
예제 #8
0
class TestCustomer(unittest.TestCase):
    @classmethod
    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def setUp(cls, mock_get):
        w = Workspace(workspace_id="123", token="456")
        cls.node = w.get_node("123")
        cls.customers = cls.node.get_customers()
        cls.headers_expected = {
            'Authorization': 'Bearer 456',
            'Content-Type': 'application/json'
        }
        cls.base_url_events = 'https://api.contactlab.it/hub/v1/workspaces/123/events'
        cls.base_url_customer = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'

    @classmethod
    def tearDown(cls):
        pass

    def test_customer_base(self):
        for customer in self.customers:
            assert type(customer.base) is Properties, type(customer.base)

    def test_customer_tags(self):
        tags = self.customers[0].tags
        assert type(tags) is Properties, type(tags)
        assert type(tags.auto) is ReadOnlyList, type(tags.auto)
        assert type(tags.manual) is ReadOnlyList, type(tags.manual)
        assert tags.auto[0] == 'auto', tags.auto[0]
        assert tags.manual[0] == 'manual', tags.manual[0]

    def test_customer_tags_wrog_attr(self):
        try:
            self.customers[0].tags.attr
        except AttributeError as e:
            assert 'attr' in str(e), str(e)

    def test_customer_tags_empty(self):
        tags = self.customers[1].tags
        assert type(tags) is Properties, type(tags)
        assert type(tags.auto) is ReadOnlyList, type(tags.auto)
        assert type(tags.manual) is ReadOnlyList, type(tags.manual)
        assert len(tags.auto) == 0, len(tags.auto)
        assert len(tags.manual) == 0, len(tags.manual)

    def test_customer_contacts_other_contacts(self):
        other_contact = self.customers[0].base.contacts.otherContacts[0]
        assert type(other_contact) is Properties, type(other_contact)
        assert other_contact.name == 'name', other_contact.name
        assert other_contact.value == 'value', other_contact.value

    def test_customer_contacts_mobile_devices(self):
        mobile_device = self.customers[0].base.contacts.mobileDevices[0]
        assert type(mobile_device) is Properties, type(mobile_device)
        assert mobile_device.identifier == 'identifier', mobile_device.name
        assert mobile_device.name == 'name', mobile_device.value

    def test_customer_contacts(self):
        contacts = self.customers[0].base.contacts
        assert type(contacts) is Properties, type(contacts)
        assert contacts.email == '*****@*****.**', contacts.email
        assert contacts.fax == 'fax', contacts.fax
        assert contacts.mobilePhone == 'mobilePhone', contacts.mobilePhone
        assert contacts.phone == 'phone', contacts.phone
        assert type(contacts.otherContacts) is ReadOnlyList, type(
            contacts.otherContacts)
        assert type(contacts.mobileDevices) is ReadOnlyList, type(
            contacts.mobileDevices)

    def test_customer_contacts_other_contacts_empty(self):
        other_contacts = self.customers[1].base.contacts.otherContacts
        assert len(other_contacts) == 0, len(other_contacts)

    def test_customer_contacts_mobile_devices_empty(self):
        mobile_devices = self.customers[1].base.contacts.mobileDevices
        assert len(mobile_devices) == 0, len(mobile_devices)

    def test_customer_contacts_empty(self):
        contacts = self.customers[1].base.contacts
        assert type(contacts) is Properties, type(contacts)
        assert contacts.fax is None, contacts.fax
        assert contacts.mobilePhone is None, contacts.mobilePhone
        assert contacts.phone is None, contacts.phone
        assert type(contacts.otherContacts) is ReadOnlyList, type(
            contacts.otherContacts)
        assert type(contacts.mobileDevices) is ReadOnlyList, type(
            contacts.mobileDevices)

    def test_customer_credentials(self):
        credentials = self.customers[0].base.credential
        assert type(credentials) is Properties, type(credentials)
        assert credentials.username == 'username', credentials.username
        assert credentials.password == 'password', credentials.password

    def test_customer_credentials_empty(self):
        credentials = self.customers[1].base.credential
        assert credentials is None, credentials

    def test_customer_education(self):
        educations = self.customers[0].base.educations
        assert type(educations) is ReadOnlyList, type(educations)
        education = educations[0]
        assert type(education) is Education, type(education)
        assert education.schoolType == Education.SCHOOL_TYPES.COLLEGE, education.schoolType
        assert education.schoolName == 'schoolName', education.schoolName
        assert education.schoolConcentration == 'schoolConcentration', education.schoolConcentration
        assert education.startYear == 1994, education.startYear
        assert education.endYear == 2000, education.endYear
        assert education.isCurrent, education.isCurrent

    def test_customer_unexsistant_attribute(self):
        educations = self.customers[0].base.educations
        assert type(educations) is ReadOnlyList, type(educations)
        education = educations[0]
        try:
            attr = education.attr
        except AttributeError as e:
            assert 'attr' in str(e), str(e)

    def test_customer_education_empty(self):
        educations = self.customers[1].base.educations
        assert type(educations) is ReadOnlyList, type(educations)
        assert len(educations) == 0, len(educations)

    def test_customer_subscriptions(self):
        subscriptions = self.customers[0].base.subscriptions
        assert type(subscriptions) is ReadOnlyList, type(subscriptions)
        subscription = subscriptions[0]
        assert type(subscription) is Subscription, type(subscription)
        assert subscription.id == "01", subscription.id
        assert subscription.name == "name", subscription.name
        assert subscription.type == "type", subscription.type
        assert subscription.subscribed, subscription.subscribed
        # assert type(subscription.startDate) is datetime, type(subscription.startDate)
        # assert type(subscription.endDate) is datetime, type(subscription.endDate)
        assert subscription.subscriberId == "subscriberId", subscription.id
        # assert type(subscription.registeredAt) is datetime, type(subscription.registeredAt)
        # assert type(subscription.updatedAt) is datetime, type(subscription.updatedAt)
        assert type(subscription.preferences) is ReadOnlyList, type(
            subscription.preferences)

    def test_customer_subscriptions_preferences(self):
        preferences = self.customers[0].base.subscriptions[0].preferences
        assert type(preferences) is ReadOnlyList, type(preferences)
        preference = preferences[0]
        assert type(preference) is Properties, type(preference)
        assert preference.key == "key", preference.key
        assert preference.value == "value", preference.value

    def test_customer_subscriptions_empty(self):
        subscriptions = self.customers[1].base.subscriptions
        assert type(subscriptions) is ReadOnlyList, type(subscriptions)
        assert len(subscriptions) == 0, len(subscriptions)

    def test_customer_jobs(self):
        jobs = self.customers[0].base.jobs
        assert type(jobs) is ReadOnlyList, type(jobs)
        job = jobs[0]
        assert type(job) is Job, type(job)
        assert job.companyIndustry == 'companyIndustry', job.companyIndustry
        assert job.companyName == 'companyName', job.companyName
        assert job.jobTitle == 'jobTitle', job.jobTitle
        assert job.isCurrent, job.isCurrent

    def test_customer_like(self):
        likes = self.customers[0].base.likes
        assert type(likes) is ReadOnlyList, type(likes)
        like = likes[0]
        assert type(like) is Like, type(like)

    def test_customer_jobs_empty(self):
        jobs = self.customers[1].base.jobs
        assert type(jobs) is ReadOnlyList, type(jobs)
        assert len(jobs) == 0, len(jobs)

    def test_customer_address(self):
        address = self.customers[0].base.address
        assert type(address) is Properties, type(address)
        assert address.street == 'street', address.street
        assert address.city == 'city', address.city
        assert address.country == 'country', address.country
        assert address.province == 'province', address.province
        assert address.zip == 'zip', address.zip
        assert type(address.geo) is Properties, type(address.geo)

    def test_customer_address_geo(self):
        geo = self.customers[0].base.address.geo
        assert type(geo.lat) is int, type(geo.lat)
        assert type(geo.lon) is int, type(geo.lon)

    def test_customer_address_empty(self):
        address = self.customers[1].base.address
        assert address is None, address

    def test_customer_social_profile(self):
        social_profile = self.customers[0].base.socialProfile
        assert social_profile.facebook == 'facebook', social_profile.facebook
        assert social_profile.google == 'google', social_profile.google
        assert social_profile.instagram == 'instagram', social_profile.instagram
        assert social_profile.linkedin == 'linkedin', social_profile.linkedin
        assert social_profile.qzone == 'qzone', social_profile.qzone
        assert social_profile.twitter == 'twitter', social_profile.twitter

    def test_customer_social_profile_empty(self):
        social_profile = self.customers[1].base.socialProfile
        assert social_profile is None, social_profile

    def test_customer_unexistent_attr(self):
        with self.assertRaises(AttributeError) as context:
            attr = self.customers[0].attr
        self.assertTrue('attr' in str(context.exception))

    def test_customer_sett_attr(self):
        self.customers[0].externalId = 3
        assert self.customers[0].externalId == 3, self.customers[0].externalId

    def test_customer_address_unexistent_attr(self):
        with self.assertRaises(AttributeError) as context:
            attr = self.customers[0].base.address.attr
        self.assertTrue('attr' in str(context.exception))

    def test_customer_contacts_unexistent_attr(self):
        with self.assertRaises(AttributeError) as context:
            attr = self.customers[0].base.contacts.attr
        self.assertTrue('attr' in str(context.exception))

    def test_customer_base_unexistent_attr(self):
        with self.assertRaises(AttributeError) as context:
            attr = self.customers[0].base.attr
        self.assertTrue('attr' in str(context.exception))

    def test_customer_subscription_unexistent_attr(self):
        with self.assertRaises(AttributeError) as context:
            attr = self.customers[0].base.subscriptions[0].attr
        self.assertTrue('attr' in str(context.exception))

    def test_customer_properties_unexistent_attr(self):
        with self.assertRaises(AttributeError) as context:
            p = Properties({'attributo': 1})
            attr = p.attr
        self.assertTrue('attr' in str(context.exception))

    def test_customer_job_unexistent_attr(self):
        with self.assertRaises(AttributeError) as context:
            attr = self.customers[0].base.jobs[0].attr
        self.assertTrue('attr' in str(context.exception))

    def test_customer_like_unexistent_attr(self):
        with self.assertRaises(AttributeError) as context:
            attr = self.customers[0].base.likes[0].attr
        self.assertTrue('attr' in str(context.exception))

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_event_response'))
    def test_all_events(self, mock_get_event):
        events = self.customers[0].get_events()
        params_expected = {'customerId': self.customers[0].id}
        mock_get_event.assert_called_with(self.base_url_events,
                                          params=params_expected,
                                          headers=self.headers_expected)
        assert isinstance(events, PaginatedList), type(events)
        assert events[0].type == Event.TYPES.ADDED_COMPARE, events[0].type

    def test_all_events_new_customer(self):
        try:
            Customer(node=self.node).get_events()
        except Exception as e:
            assert 'events' in str(e), str(e)

    def test_customer_create_extra(self):
        c = Customer(node=self.node, extra='extra')
        assert c.attributes['extra'] == 'extra', c.attributes['extra']
        assert c.extra == 'extra', c.extra

    @mock.patch('requests.delete',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_delete(self, mock_delete):
        id = self.customers[0].id
        self.customers[0].delete()
        mock_delete.assert_called_with(self.base_url_customer + '/' + id,
                                       headers=self.headers_expected)

    def test_delete_created_new_customer(self):
        try:
            Customer(node=self.node).delete()
        except KeyError as e:
            assert 'id' in str(e), str(e)

    @mock.patch('requests.delete',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response',
                    status_code=401))
    def test_delete_not_permitted(self, mock_delete):
        try:
            self.customers[0].delete()
        except HTTPError as e:
            assert 'Message' in str(e), str(e)

    @mock.patch('requests.delete',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_delete_created(self, mock_delete):
        Customer(id='01', node=self.node).delete()
        mock_delete.assert_called_with(self.base_url_customer + '/01',
                                       headers=self.headers_expected)

    @mock.patch(
        'contacthub._api_manager._api_customer._CustomerAPIManager.post')
    def test_post_customer_creation_first_method(self, mock_post):
        expected_body = {
            'base': {
                'contacts': {
                    'email': '*****@*****.**'
                }
            },
            'extra': 'extra',
            'extended': {
                'prova': 'prova'
            },
            'tags': {
                'auto': ['auto'],
                'manual': ['manual']
            }
        }
        mock_post.return_value = json.loads(
            FakeHTTPResponse(resp_path='tests/util/fake_post_response').text)
        c = Customer(
            node=self.node,
            base=Properties(contacts=Properties(email='*****@*****.**')))

        c.extra = 'extra'
        c.extended.prova = 'prova'
        c.tags.auto = ['auto']
        c.tags.manual = ['manual']

        c.post()
        mock_post.assert_called_with(body=expected_body, force_update=False)

    # @mock.patch('contacthub._api_manager._api_customer._CustomerAPIManager.post')
    # def test_post_customer_creation_second_method(self, mock_post):
    #     expected_body = {'base': {'contacts': {'email': '*****@*****.**'}}, 'extra': 'extra'}
    #     mock_post.return_value = json.loads(FakeHTTPResponse(resp_path='tests/util/fake_post_response').text)
    #     c = Customer(base=Properties(), node=self.node)
    #     c.base.contacts = Properties(email='*****@*****.**')
    #     c.extra = 'extra'
    #     posted = c.post()
    #     mock_post.assert_called_with(body=expected_body, force_update=False)
    #     assert isinstance(posted, Customer), type(posted)
    #     assert posted.base.contacts.email == c.base.contacts.email, posted.base.contacts.email
    #     assert posted.extra == c.extra, posted.extra

    @mock.patch(
        'contacthub._api_manager._api_customer._CustomerAPIManager.post')
    def test_post_customer_creation_second_method(self, mock_post):
        expected_body = {
            'base': {
                'contacts': {
                    'email': '*****@*****.**'
                }
            },
            'extra': 'extra',
            'extended': {},
            'tags': {
                'auto': [],
                'manual': []
            }
        }
        mock_post.return_value = json.loads(
            FakeHTTPResponse(resp_path='tests/util/fake_post_response').text)
        c = Customer(node=self.node, base=Properties())
        c.base.contacts = {'email': '*****@*****.**'}
        c.extra = 'extra'
        c.post()
        mock_post.assert_called_with(body=expected_body, force_update=False)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch(self, mock_patch):
        self.customers[0].base.firstName = 'fn'
        self.customers[0].patch()
        body = {'base': {'firstName': 'fn'}}
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.put',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_put(self, mock_patch):
        self.customers[0].base.firstName = 'fn'
        self.customers[0].put()
        body = deepcopy(self.customers[0].attributes)
        body.pop('updatedAt')
        body.pop('registeredAt')
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_entity(self, mock_patch):
        self.customers[0].extended = Properties(a=1, prova=Properties(b=1))
        self.customers[0].patch()
        body = {
            'extended': {
                'prova': {
                    'b': 1,
                    'oggetto': None,
                    'list': []
                },
                'a': 1
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_entity_extended_and_base(self, mock_patch):
        self.customers[0].extended = Properties(a=1, prova=Properties(b=1))
        self.customers[0].base.firstName = 'fn'
        self.customers[0].patch()
        body = {
            'extended': {
                'prova': {
                    'b': 1,
                    'oggetto': None,
                    'list': []
                },
                'a': 1
            },
            'base': {
                'firstName': 'fn'
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_extended_entity_and_base_entity(self, mock_patch):
        self.customers[0].extended = Properties(a=1, prova=Properties(b=1))
        self.customers[0].base = Properties(contacts=Properties(email='email'))
        self.customers[0].patch()
        body = {
            'extended': {
                'prova': {
                    'b': 1,
                    'oggetto': None,
                    'list': []
                },
                'a': 1
            },
            'base': {
                'pictureUrl': None,
                'title': None,
                'prefix': None,
                'firstName': None,
                'lastName': None,
                'middleName': None,
                'gender': None,
                'dob': None,
                'locale': None,
                'timezone': None,
                'contacts': {
                    'email': 'email',
                    'fax': None,
                    'mobilePhone': None,
                    'phone': None,
                    'otherContacts': [],
                    'mobileDevices': []
                },
                'address': None,
                'credential': None,
                'educations': [],
                'likes': [],
                'socialProfile': None,
                'jobs': [],
                'subscriptions': []
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_entity_with_entity(self, mock_patch):
        self.customers[0].extended = Properties(a=1, prova=Properties(b=1))
        self.customers[0].base.contacts = Properties(email='email')
        self.customers[0].patch()
        body = {
            'extended': {
                'prova': {
                    'b': 1,
                    'oggetto': None,
                    'list': []
                },
                'a': 1
            },
            'base': {
                'contacts': {
                    'email': 'email',
                    'fax': None,
                    'mobilePhone': None,
                    'phone': None,
                    'otherContacts': [],
                    'mobileDevices': []
                }
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_entity_with_rename(self, mock_patch):
        self.customers[0].extended = Properties(a=1, prova=Properties(b=1))
        self.customers[0].base.contacts = Properties(email1='email')
        self.customers[0].patch()
        body = {
            'extended': {
                'prova': {
                    'b': 1,
                    'oggetto': None,
                    'list': []
                },
                'a': 1
            },
            'base': {
                'contacts': {
                    'email': None,
                    'email1': 'email',
                    'fax': None,
                    'mobilePhone': None,
                    'phone': None,
                    'otherContacts': [],
                    'mobileDevices': []
                }
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_entity_with_rename_dict(self, mock_patch):
        self.customers[0].extended = Properties(a=1, prova=Properties(b=1))
        self.customers[0].base.contacts = Properties(email1=Properties(a=1))
        self.customers[0].patch()
        body = {
            'extended': {
                'prova': {
                    'b': 1,
                    'oggetto': None,
                    'list': []
                },
                'a': 1
            },
            'base': {
                'contacts': {
                    'email': None,
                    'email1': {
                        'a': 1
                    },
                    'fax': None,
                    'mobilePhone': None,
                    'phone': None,
                    'otherContacts': [],
                    'mobileDevices': []
                }
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_entity_list(self, mock_patch):
        self.customers[0].extended = Properties(a=1, prova=Properties(b=1))
        self.customers[0].base.contacts.otherContacts = [
            Properties(email1=Properties(a=1))
        ]
        self.customers[0].patch()
        body = {
            'extended': {
                'prova': {
                    'b': 1,
                    'oggetto': None,
                    'list': []
                },
                'a': 1
            },
            'base': {
                'contacts': {
                    'otherContacts': [{
                        'email1': {
                            'a': 1
                        }
                    }]
                }
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_entity_new_list(self, mock_patch):
        self.customers[0].base.contacts = Properties(email='email')
        self.customers[0].base.contacts.otherContacts = [
            Properties(email1=Properties(a=1))
        ]
        self.customers[0].patch()
        body = {
            'base': {
                'contacts': {
                    'email': 'email',
                    'fax': None,
                    'mobilePhone': None,
                    'phone': None,
                    'mobileDevices': [],
                    'otherContacts': [{
                        'email1': {
                            'a': 1
                        }
                    }]
                }
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_entity_new_list_with_entities(self, mock_patch):
        self.customers[0].base.contacts = Properties(email='email')
        self.customers[0].base.contacts.otherContacts = [
            Properties(email1=Properties(a=Properties(b=1)))
        ]
        self.customers[0].patch()
        body = {
            'base': {
                'contacts': {
                    'email': 'email',
                    'fax': None,
                    'mobilePhone': None,
                    'phone': None,
                    'mobileDevices': [],
                    'otherContacts': [{
                        'email1': {
                            'a': {
                                'b': 1
                            }
                        }
                    }]
                }
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_all_extended(self, mock_patch):
        self.customers[0].extended = Properties()
        self.customers[0].patch()
        body = {'extended': {'prova': None}}
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_all_base(self, mock_patch):
        self.customers[0].base = Properties()
        self.customers[0].patch()
        body = {
            'base': {
                'pictureUrl': None,
                'title': None,
                'prefix': None,
                'firstName': None,
                'lastName': None,
                'middleName': None,
                'gender': None,
                'dob': None,
                'locale': None,
                'timezone': None,
                'contacts': None,
                'address': None,
                'credential': None,
                'educations': [],
                'likes': [],
                'socialProfile': None,
                'jobs': [],
                'subscriptions': []
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_patch_elem_in_list(self, mock_patch):
        self.customers[0].base.contacts.otherContacts[0].type = 'TYPE'
        self.customers[0].patch()
        body = {
            'base': {
                'contacts': {
                    'otherContacts': [{
                        'name': 'name',
                        'type': 'TYPE',
                        'value': 'value'
                    }, {
                        'name': 'Casa di piero',
                        'type': 'PHONE',
                        'value': '12343241'
                    }]
                }
            }
        }
        mock_patch.assert_called_with(self.base_url_customer + '/' +
                                      self.customers[0].id,
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.post',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_conflict_response',
                    status_code=409))
    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response',
                    status_code=200))
    def test_post_with_force_update(self, mock_patch, mock_post):
        body = {
            'extra': 'extra',
            'base': {
                'contacts': {
                    'email': '*****@*****.**'
                }
            }
        }
        c = Customer.from_dict(node=self.node, attributes=body)
        posted = c.post(force_update=True)
        mock_patch.assert_called_with(self.base_url_customer + '/01',
                                      headers=self.headers_expected,
                                      json=body)

    def test_create_customer_with_default_schema(self):
        c = Customer(node=self.node,
                     default_attributes={
                         'prop': {
                             'prop1': 'value1'
                         },
                         'prop2': 'value2'
                     },
                     prop3=Properties(prop4='value4'))
        internal = {
            'prop': {
                'prop1': 'value1'
            },
            'prop2': 'value2',
            'prop3': {
                'prop4': 'value4'
            }
        }
        assert c.attributes == internal, c.attributes

    def test_from_dict_no_props(self):
        c = Customer.from_dict(node=self.node)
        assert c.attributes == {}, c.attributes
        prop = {}
        c = Customer.from_dict(node=self.node, attributes=prop)
        assert c.attributes is prop, c.attributes

    def test_customer_patch_new_prop(self):
        c = Customer(node=self.node,
                     default_attributes={
                         'prop': {
                             'prop1': 'value1'
                         },
                         'prop2': 'value2'
                     },
                     prop3=Properties(prop4='value4'))

        c.prop5 = Properties(prop6='value5')
        assert c.mute == {'prop5': {'prop6': 'value5'}}, c.mute

    @mock.patch('requests.put', return_value=FakeHTTPResponse())
    def test_put_no_timezone(self, mock_put):
        c = Customer(node=self.node, id='01')
        c.base.timezone = None
        c.put()
        params_expected = {
            'id': '01',
            'base': {
                'contacts': {},
                'timezone': 'Europe/Rome'
            },
            'extended': {},
            'tags': {
                'manual': [],
                'auto': []
            }
        }
        mock_put.assert_called_with(self.base_url_customer + '/01',
                                    headers=self.headers_expected,
                                    json=params_expected)
class TestNode(TestSuite):
    @classmethod
    def setUp(cls):
        w = Workspace(workspace_id=123, token=456)
        cls.node = w.get_node(123)
        cls.headers_expected = {
            'Authorization': 'Bearer 456',
            'Content-Type': 'application/json'
        }
        cls.base_url = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'
        cls.base_events_url = 'https://api.contactlab.it/hub/v1/workspaces/123/events'

    @classmethod
    def tearDown(cls):
        pass

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_get_customers(self, mock_get):
        customers = self.node.get_customers()

        base_url = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'
        params_expected = {'nodeId': '123'}
        mock_get.assert_called_with(base_url,
                                    params=params_expected,
                                    headers=self.headers_expected)
        assert type(customers) is PaginatedList, type(customers)
        assert customers[0].enabled, customers[0]

    @mock.patch('requests.get')
    def test_query(self, mock_get):
        mock_get.return_value = FakeHTTPResponse(
            resp_path='tests/util/fake_query_response')
        query_expected = {
            'name': 'query',
            'query': {
                'type': 'simple',
                'name': 'query',
                'are': {
                    'condition': {
                        'type':
                        'composite',
                        'conditions': [{
                            'type': 'atomic',
                            'attribute': 'base.contacts.email',
                            'operator': 'EQUALS',
                            'value': '*****@*****.**'
                        }, {
                            'type': 'atomic',
                            'attribute': 'extra',
                            'operator': 'EQUALS',
                            'value': 'Ciao'
                        }],
                        'conjunction':
                        'and'
                    }
                }
            }
        }

        customers_query = self.node.query(Customer).filter(
            (Customer.base.contacts.email == '*****@*****.**')
            & (Customer.extra == 'Ciao')).all()
        params_expected = {
            'nodeId': '123',
            'query': json.dumps(query_expected)
        }
        base_url = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'

        mock_get.assert_called_with(base_url,
                                    params=params_expected,
                                    headers=self.headers_expected)

        assert customers_query[
            0].base.contacts.email == '*****@*****.**', customers_query[
                0].base.contacts.email
        assert customers_query[0].extra == 'Ciao', customers_query[0].extra

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_get_customer(self, mock_get):
        customers = self.node.get_customer(id='01')
        self.headers_expected = {
            'Authorization': 'Bearer 456',
            'Content-Type': 'application/json'
        }
        base_url = 'https://api.contactlab.it/hub/v1/workspaces/123/customers/01'
        mock_get.assert_called_with(base_url, headers=self.headers_expected)

    def test_get_customer_id_external(self):
        try:
            customers = self.node.get_customer(id='01', external_id='03')
            assert False
        except ValueError as e:
            assert 'id' in str(e), str(e)

    def test_get_customer_not_id_external(self):
        try:
            customers = self.node.get_customer()
            assert False
        except ValueError as e:
            assert 'id' in str(e), str(e)

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_get_customer_external_id(self, mock_get):
        customers = self.node.get_customer(external_id='01')
        self.headers_expected = {
            'Authorization': 'Bearer 456',
            'Content-Type': 'application/json'
        }
        base_url = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'
        mock_get.assert_called_with(base_url,
                                    headers=self.headers_expected,
                                    params={
                                        'externalId': '01',
                                        'nodeId': '123'
                                    })
        assert isinstance(customers, list), type(customers)

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_external_single_response'))
    def test_get_customer_external_id_single(self, mock_get):
        customers = self.node.get_customer(external_id='01')
        assert isinstance(customers, Customer), type(customers)
        self.headers_expected = {
            'Authorization': 'Bearer 456',
            'Content-Type': 'application/json'
        }
        base_url = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'
        mock_get.assert_called_with(base_url,
                                    headers=self.headers_expected,
                                    params={
                                        'externalId': '01',
                                        'nodeId': '123'
                                    })

    @mock.patch('requests.delete', return_value=FakeHTTPResponse())
    def test_delete_customer(self, mock_get):
        c = Customer(node=self.node, id='01')
        self.node.delete_customer(c.id)
        mock_get.assert_called_with(self.base_url + '/01',
                                    headers=self.headers_expected)

    @mock.patch('requests.post', return_value=FakeHTTPResponse())
    def test_add_customer(self, mock_get):
        c = Customer(node=self.node,
                     base=Properties(contacts=Properties(email='email')))
        self.node.add_customer(**c.to_dict())
        body = {
            'nodeId': self.node.node_id,
            'base': {
                'contacts': {
                    'email': 'email'
                }
            },
            'extended': {},
            'tags': {
                'auto': [],
                'manual': []
            }
        }
        mock_get.assert_called_with(self.base_url,
                                    headers=self.headers_expected,
                                    json=body)

    @mock.patch('requests.post', return_value=FakeHTTPResponse())
    def test_add_customer_extended(self, mock_get):
        c = Customer(node=self.node,
                     base=Properties(contacts=Properties(email='email')))
        c.extended.prova = 'prova'
        self.node.add_customer(**c.to_dict())
        body = {
            'nodeId': self.node.node_id,
            'base': {
                'contacts': {
                    'email': 'email'
                }
            },
            'extended': {
                'prova': 'prova'
            },
            'tags': {
                'auto': [],
                'manual': []
            }
        }
        mock_get.assert_called_with(self.base_url,
                                    headers=self.headers_expected,
                                    json=body)

    @mock.patch('requests.post', return_value=FakeHTTPResponse())
    def test_add_customer_tags(self, mock_get):
        c = Customer(node=self.node,
                     base=Properties(contacts=Properties(email='email')))
        c.extended.prova = 'prova'
        c.tags.auto = ['auto']
        c.tags.manual = ['manual']
        self.node.add_customer(**c.to_dict())
        body = {
            'nodeId': self.node.node_id,
            'base': {
                'contacts': {
                    'email': 'email'
                }
            },
            'extended': {
                'prova': 'prova'
            },
            'tags': {
                'auto': ['auto'],
                'manual': ['manual']
            }
        }
        mock_get.assert_called_with(self.base_url,
                                    headers=self.headers_expected,
                                    json=body)

    @mock.patch('requests.patch', return_value=FakeHTTPResponse())
    def test_update_customer_not_full(self, mock_patch):
        c = Customer(node=self.node,
                     id='01',
                     base=Properties(contacts=Properties(email='email')))
        c.extra = 'extra'
        self.node.update_customer(c.id, **c.get_mutation_tracker())
        body = {'extra': 'extra'}
        mock_patch.assert_called_with(self.base_url + '/01',
                                      headers=self.headers_expected,
                                      json=body)

    @mock.patch('requests.put', return_value=FakeHTTPResponse())
    def test_update_customer_full(self, mock_get):
        c = Customer(
            node=self.node,
            id='01',
            base=Properties(contacts=Properties(email='email', fax='fax')))
        c.base.contacts.email = 'email1234'
        self.node.update_customer(full_update=True, **c.to_dict())
        body = {
            'id': '01',
            'base': {
                'contacts': {
                    'email': 'email1234',
                    'fax': 'fax'
                }
            },
            'extended': {},
            'tags': {
                'auto': [],
                'manual': []
            }
        }
        mock_get.assert_called_with(self.base_url + '/01',
                                    headers=self.headers_expected,
                                    json=body)

    @mock.patch('requests.post',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_session_response'))
    def test_add_customer_session(self, mock_get):
        s_id = self.node.create_session_id()
        body = {'value': str(s_id)}
        self.node.add_customer_session(session_id=s_id, customer_id='01')
        mock_get.assert_called_with(self.base_url + '/01/sessions',
                                    headers=self.headers_expected,
                                    json=body)

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_add_tag(self, mock_patch, mock_get):
        self.node.add_tag(customer_id='b6023673-b47a-4654-a53c-74bbc0204a20',
                          tag='tag1')
        mock_get.assert_called_with(self.base_url +
                                    '/b6023673-b47a-4654-a53c-74bbc0204a20',
                                    headers=self.headers_expected)
        mock_patch.assert_called_with(
            self.base_url + '/b6023673-b47a-4654-a53c-74bbc0204a20',
            headers=self.headers_expected,
            json={'tags': {
                'manual': ['manual', 'tag1']
            }})

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_remove_tag(self, mock_patch, mock_get):
        self.node.remove_tag(
            customer_id='b6023673-b47a-4654-a53c-74bbc0204a20', tag='manual')
        mock_get.assert_called_with(self.base_url +
                                    '/b6023673-b47a-4654-a53c-74bbc0204a20',
                                    headers=self.headers_expected)
        mock_patch.assert_called_with(self.base_url +
                                      '/b6023673-b47a-4654-a53c-74bbc0204a20',
                                      headers=self.headers_expected,
                                      json={'tags': {
                                          'manual': []
                                      }})

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    @mock.patch('requests.patch',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_post_response'))
    def test_remove_tag_unexistent(self, mock_patch, mock_get):

        try:
            self.node.remove_tag(
                customer_id='b6023673-b47a-4654-a53c-74bbc0204a20', tag='asd')
            mock_get.assert_called_with(
                self.base_url + '/b6023673-b47a-4654-a53c-74bbc0204a20',
                headers=self.headers_expected)
        except ValueError as e:
            assert 'Tag' in str(e), str(e)

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    @mock.patch(
        'requests.post',
        return_value=FakeHTTPResponse(resp_path='tests/util/fake_job_response')
    )
    def test_add_job(self, mock_post, mock_get):
        j = self.node.add_job(customer_id='123',
                              jobTitle='jobTitle',
                              companyName='companyName',
                              companyIndustry='companyIndustry',
                              isCurrent=True,
                              id='01',
                              startDate='1994-10-06',
                              endDate='1994-10-06')
        assert isinstance(j, Job), type(j)
        assert j.isCurrent, j.isCurrent
        mock_post.assert_called_with(self.base_url + '/123/jobs',
                                     headers=self.headers_expected,
                                     json=dict(
                                         jobTitle='jobTitle',
                                         companyName='companyName',
                                         companyIndustry='companyIndustry',
                                         isCurrent=True,
                                         id='01',
                                         startDate='1994-10-06',
                                         endDate='1994-10-06'))

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    @mock.patch('requests.post',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_subscription_response'))
    def test_add_subscription(self, mock_post, mock_get):
        s = self.node.add_subscription(customer_id='123',
                                       id='01',
                                       name='name',
                                       kind='SERVICE')
        assert isinstance(s, Subscription), type(s)
        assert s.id == '01'
        mock_post.assert_called_with(self.base_url + '/123/subscriptions',
                                     headers=self.headers_expected,
                                     json=dict(id='01',
                                               name='name',
                                               kind='SERVICE'))

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    @mock.patch('requests.post',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_education_response'))
    def test_add_education(self, mock_post, mock_get):
        e = self.node.add_education(customer_id='123',
                                    id='01',
                                    schoolType='schoolType',
                                    schoolName='schoolName',
                                    schoolConcentration='schoolConcentration',
                                    isCurrent=True,
                                    startYear='1994',
                                    endYear='2000')
        assert isinstance(e, Education), type(e)
        assert e.isCurrent, e.isCurrent
        mock_post.assert_called_with(
            self.base_url + '/123/educations',
            headers=self.headers_expected,
            json=dict(schoolType='schoolType',
                      schoolName='schoolName',
                      schoolConcentration='schoolConcentration',
                      isCurrent=True,
                      id='01',
                      startYear='1994',
                      endYear='2000'))

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    @mock.patch('requests.post',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_like_response'))
    def test_add_like(self, mock_post, mock_get):
        now = datetime.now()
        now_s = now.strftime("%Y-%m-%dT%H:%M:%SZ")
        l = self.node.add_like(customer_id='123',
                               name='name',
                               category='category',
                               createdTime=now,
                               id='01')
        assert isinstance(l, Like), type(l)
        assert l.name == 'name', l.name
        mock_post.assert_called_with(self.base_url + '/123/likes',
                                     headers=self.headers_expected,
                                     json=dict(name='name',
                                               category='category',
                                               createdTime=now_s,
                                               id='01'))

    @mock.patch('requests.delete',
                return_value=FakeHTTPResponse(resp_path=None))
    def test_remove_job(self, mock_delete):
        self.node.remove_job(customer_id='01', job_id='02')
        mock_delete.assert_called_with(self.base_url + '/01/jobs/02',
                                       headers=self.headers_expected)

    @mock.patch('requests.delete',
                return_value=FakeHTTPResponse(resp_path=None))
    def test_remove_subscription(self, mock_delete):
        self.node.remove_subscription(customer_id='01', subscription_id='02')
        mock_delete.assert_called_with(self.base_url + '/01/subscriptions/02',
                                       headers=self.headers_expected)

    @mock.patch('requests.delete',
                return_value=FakeHTTPResponse(resp_path=None))
    def test_remove_education(self, mock_delete):
        self.node.remove_education(customer_id='01', education_id='02')
        mock_delete.assert_called_with(self.base_url + '/01/educations/02',
                                       headers=self.headers_expected)

    @mock.patch('requests.delete',
                return_value=FakeHTTPResponse(resp_path=None))
    def test_remove_like(self, mock_delete):
        self.node.remove_like(customer_id='01', like_id='02')
        mock_delete.assert_called_with(self.base_url + '/01/likes/02',
                                       headers=self.headers_expected)

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    @mock.patch('requests.put',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_like_response'))
    def test_update_like(self, mock_put, mock_get):
        now = datetime.now()
        now_s = now.strftime("%Y-%m-%dT%H:%M:%SZ")
        l1 = Like(name='name',
                  category='category1',
                  createdTime=now,
                  id='01',
                  customer=Customer(node=self.node, id='123'))
        l = self.node.update_like(customer_id='123', **l1.to_dict())
        assert isinstance(l, Like), type(l)
        assert l.name == 'name', l.name
        mock_put.assert_called_with(self.base_url + '/123/likes/01',
                                    headers=self.headers_expected,
                                    json=dict(name='name',
                                              category='category1',
                                              createdTime=now_s))

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    @mock.patch('requests.put',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_education_response'))
    def test_update_education(self, mock_post, mock_get):
        e1 = Education(schoolType='schoolType1',
                       schoolName='schoolName1',
                       schoolConcentration='schoolConcentration1',
                       isCurrent=True,
                       id='01',
                       startYear='1994',
                       endYear='2000',
                       customer=Customer(node=self.node, id='123'))
        e = self.node.update_education(customer_id='123', **e1.to_dict())
        assert isinstance(e, Education), type(e)
        assert e.isCurrent, e.isCurrent
        mock_post.assert_called_with(
            self.base_url + '/123/educations/01',
            headers=self.headers_expected,
            json=dict(schoolType='schoolType1',
                      schoolName='schoolName1',
                      schoolConcentration='schoolConcentration1',
                      isCurrent=True,
                      startYear='1994',
                      endYear='2000'))

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    @mock.patch('requests.put',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_education_response'))
    def test_update_subscription(self, mock_post, mock_get):
        s1 = Subscription(name='name',
                          kind='SERVICE',
                          id='01',
                          customer=Customer(node=self.node, id='123'))
        s = self.node.update_subscription(customer_id='123', **s1.to_dict())
        assert isinstance(s, Subscription), type(s)
        assert s.id == '01', s.id
        mock_post.assert_called_with(self.base_url + '/123/subscriptions/01',
                                     headers=self.headers_expected,
                                     json=dict(name='name', kind='SERVICE'))

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    @mock.patch(
        'requests.put',
        return_value=FakeHTTPResponse(resp_path='tests/util/fake_job_response')
    )
    def test_update_job(self, mock_post, mock_get):
        j1 = Job(jobTitle='jobTitle1',
                 companyName='companyName',
                 companyIndustry='companyIndustry1',
                 isCurrent=True,
                 id='01',
                 startDate='1994-10-06',
                 endDate='1994-10-06',
                 customer=Customer(node=self.node, id='123'))
        j = self.node.update_job(customer_id='123', **j1.to_dict())
        assert isinstance(j, Job), type(j)
        assert j.isCurrent, j.isCurrent
        mock_post.assert_called_with(self.base_url + '/123/jobs/01',
                                     headers=self.headers_expected,
                                     json=dict(
                                         jobTitle='jobTitle1',
                                         companyName='companyName',
                                         companyIndustry='companyIndustry1',
                                         isCurrent=True,
                                         startDate='1994-10-06',
                                         endDate='1994-10-06'))

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_event_response'))
    def test_get_all_events(self, mock_get):
        e = self.node.get_events(
            customer_id='8b321dce-53c4-4029-8388-1938efa2090c')
        mock_get.assert_called_with(
            self.base_events_url,
            headers=self.headers_expected,
            params={'customerId': '8b321dce-53c4-4029-8388-1938efa2090c'})
        assert isinstance(e, list), type(e)
        assert e[0].customerId == '8b321dce-53c4-4029-8388-1938efa2090c', e[
            0].customerId

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_single_event_response'))
    def test_get_event(self, mock_get):
        e = self.node.get_event(id='123')
        mock_get.assert_called_with(self.base_events_url + '/123',
                                    headers=self.headers_expected)
        assert isinstance(e, Event), type(e)
        assert e.customerId == '46cf4766-770b-4e2f-b5e2-c82273e45ab9', e.customerId

    @mock.patch(
        'requests.get',
        return_value=FakeHTTPResponse(resp_path='tests/util/fake_job_response')
    )
    def test_get_job(self, mock_get):
        j = self.node.get_customer_job(customer_id='123', job_id='456')
        mock_get.assert_called_with(self.base_url + '/123/jobs/456',
                                    headers=self.headers_expected)
        assert isinstance(j, Job), type(j)
        assert j.companyIndustry == 'companyIndustry', j.companyIndustry

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_subscription_response'))
    def test_get_subscription(self, mock_get):
        s = self.node.get_customer_subscription(customer_id='123',
                                                subscription_id='456')
        mock_get.assert_called_with(self.base_url + '/123/subscriptions/456',
                                    headers=self.headers_expected)
        assert isinstance(s, Subscription), type(s)
        assert s.preferences[0].key == 'key', s.preferences[0].key

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_like_response'))
    def test_get_like(self, mock_get):
        l = self.node.get_customer_like(customer_id='123', like_id='456')
        mock_get.assert_called_with(self.base_url + '/123/likes/456',
                                    headers=self.headers_expected)
        assert isinstance(l, Like), type(l)
        assert l.name == 'name', l.name

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_education_response'))
    def test_get_education(self, mock_get):
        e = self.node.get_customer_education(customer_id='123',
                                             education_id='456')
        mock_get.assert_called_with(self.base_url + '/123/educations/456',
                                    headers=self.headers_expected)
        assert isinstance(e, Education), type(e)
        assert e.schoolType == Education.SCHOOL_TYPES.COLLEGE, e.schoolType

    @mock.patch('requests.post',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_single_event_response'))
    def test_post_event(self, mock_post):
        self.node.add_event(a=[Properties(a='b')],
                            b='c',
                            d=Properties(f='g', h=Properties(i='j')),
                            k=dict(l=Properties(m='n', o='p')))

        mock_post.assert_called_with(self.base_events_url,
                                     headers=self.headers_expected,
                                     json={
                                         'a': [{
                                             'a': 'b'
                                         }],
                                         'b': 'c',
                                         'd': {
                                             'f': 'g',
                                             'h': {
                                                 'i': 'j'
                                             }
                                         },
                                         'k': {
                                             'l': {
                                                 'm': 'n',
                                                 'o': 'p'
                                             }
                                         }
                                     })

    @mock.patch('requests.post',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_single_event_response'))
    def test_post_event_dict(self, mock_post):
        self.node.add_event(
            **{
                'a': [{
                    'a': 'b'
                }],
                'b': 'c',
                'd': {
                    'f': 'g',
                    'h': {
                        'i': 'j'
                    }
                },
                'k': {
                    'l': {
                        'm': 'n',
                        'o': 'p'
                    }
                }
            })
        mock_post.assert_called_with(self.base_events_url,
                                     headers=self.headers_expected,
                                     json={
                                         'a': [{
                                             'a': 'b'
                                         }],
                                         'b': 'c',
                                         'd': {
                                             'f': 'g',
                                             'h': {
                                                 'i': 'j'
                                             }
                                         },
                                         'k': {
                                             'l': {
                                                 'm': 'n',
                                                 'o': 'p'
                                             }
                                         }
                                     })

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_customer_paginated(self, mock_get):
        l = self.node.get_customers().next_page()
        assert isinstance(l, PaginatedList), type(l)
        params_expected = {'nodeId': '123', 'page': 1}
        mock_get.assert_called_with(self.base_url,
                                    params=params_expected,
                                    headers=self.headers_expected)
        assert isinstance(l[0], Customer), type(l[0])

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_response_page'))
    def test_customer_paginated_exception(self, mock_get):
        try:
            l = self.node.get_customers().next_page().next_page().next_page()
        except OperationNotPermitted as e:
            assert 'Last page reached' in str(e), str(e)

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_customer_paginated_exception_prev(self, mock_get):
        try:
            l = self.node.get_customers().previous_page()
        except OperationNotPermitted as e:
            assert 'First page reached' in str(e), str(e)

    @mock.patch('requests.get',
                return_value=FakeHTTPResponse(
                    resp_path='tests/util/fake_response_page_prev'))
    def test_customer_paginated_prev(self, mock_get):
        l = self.node.get_customers().previous_page()
        assert isinstance(l, PaginatedList), type(l)
        params_expected = {'nodeId': '123'}
        mock_get.assert_called_with(self.base_url,
                                    params=params_expected,
                                    headers=self.headers_expected)
        assert isinstance(l[0], Customer), type(l[0])
        assert l.size == 10, l.size
예제 #10
0
class TestSubscription(unittest.TestCase):
    @classmethod
    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def setUp(cls, mock_get_customers):
        w = Workspace(workspace_id="123", token="456")
        cls.node = w.get_node("123")
        cls.customers = cls.node.get_customers()
        cls.headers_expected = {'Authorization': 'Bearer 456', 'Content-Type': 'application/json'}
        cls.base_url_customer = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'
        cls.customer = Customer(id='01', node=cls.node)
        cls.subscription = Subscription(customer=cls.customer, **{'id': '01'})

    @classmethod
    def tearDown(cls):
        pass

    def test_from_dict_no_attr(self):
        e = Subscription.from_dict(customer=self.customer)
        assert e.attributes == {}, e.attributes

    def test_set_job(self):
        self.subscription.name = "name"
        assert self.subscription.name == "name", self.subscription.name

    def test_to_dict(self):
        self.subscription.name = "name"
        assert self.subscription.to_dict() == {'id': '01', 'name': 'name'}

    def test_get_list(self):
        s = Subscription(customer=self.customer, **{'id': '01'})
        s.preferences = ['a']
        assert s.preferences == ['a'], s.preferences

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_customer_subscription(self, mock_get):
        customers = self.node.get_customers()
        assert customers[0].base.subscriptions[0].a == ['a'], customers[0].base.subscriptions[0].a

    @mock.patch('requests.get', return_value=FakeHTTPResponse())
    def test_customer_mute_subscription(self, mock_get):
        customers = self.node.get_customers()
        customers[0].base.subscriptions[0].kind = 'kind'
        assert customers[0].mute == {'base.subscriptions': [{'id': '01', 'name': 'name', 'type': 'type',
                                                                 'kind': 'kind', 'subscribed': True,
                                                                 'startDate': '1994-10-06', 'endDate': '1994-10-10',
                                                                 'subscriberId': 'subscriberId',
                                                                 'registeredAt': '1994-10-06',
                                                                 'updatedAt': '1994-10-06',
                                                                 'preferences': [{'key': 'key', 'value': 'value'}],
                                                                 'a': ['a']}]}, customers[0].mute

    def test_set_subscription_customer_add(self):
        self.customers[0].base.subscriptions[0].name = 'name1'
        self.customers[0].base.subscriptions += [Subscription(customer=self.customers[0], id='02')]

        mute = {'base.subscriptions': [{'id': '01', 'name': 'name1', 'type': 'type',
                                            'kind': 'SERVICE', 'subscribed': True,
                                            'startDate': '1994-10-06', 'endDate': '1994-10-10',
                                            'subscriberId': 'subscriberId',
                                            'registeredAt': '1994-10-06',
                                            'updatedAt': '1994-10-06',
                                            'preferences': [{'key': 'key', 'value': 'value'}],
                                            'a': ['a']}, {'id': '02'}]}
        assert self.customers[0].mute == mute, self.customers[0].mute

    @mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_subscription_response'))
    def test_post_job(self, mock_post):
        s = Subscription(customer=self.customer, id='01', name='name', type='type', kind='SERVICE', subscribed=True,
                         startDate='1994-10-06', endDate='1994-10-10', subscriberId='subscriberId',
                         preferences=[{'key': 'key', 'value': 'value'}])
        s.post()

        mock_post.assert_called_with(self.base_url_customer + '/' + self.customer.id + '/subscriptions',
                                     headers=self.headers_expected,
                                     json=s.attributes)
        assert self.customer.base.subscriptions[0].attributes == s.attributes, \
            (self.customer.base.subscriptions[0].attributes, s.attributes)

    @mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_subscription_response'))
    def test_post_job_create_base(self, mock_post):
        c = Customer(node=self.node, default_attributes={}, id='01')
        s = Subscription(customer=c, id='01', name='name', type='type', kind='SERVICE', subscribed=True,
                         startDate='1994-10-06', endDate='1994-10-10', subscriberId='subscriberId',
                         preferences=[{'key': 'key', 'value': 'value'}])
        s.post()

        mock_post.assert_called_with(self.base_url_customer + '/' + c.id + '/subscriptions',
                                    headers=self.headers_expected,
                                    json=s.attributes)
        assert c.base.subscriptions[0].attributes == s.attributes, (c.base.subscriptions[0].attributes, s.attributes)

    @mock.patch('requests.delete', return_value=FakeHTTPResponse(resp_path='tests/util/fake_job_response'))
    def test_delete(self, mock_post):
        s = Subscription(customer=self.customer, id='01')
        s.delete()
        mock_post.assert_called_with(self.base_url_customer + '/' + self.customer.id + '/subscriptions/01',
                                    headers=self.headers_expected)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_subscription_response'))
    def test_put(self, mock_post):
        self.customer.base.subscriptions = [self.subscription]
        self.subscription.name = 'name'
        self.subscription.type = 'type'
        self.subscription.kind = 'SERVICE'
        self.subscription.subscriberId = 'subscriberId'
        self.subscription.startDate = '1994-10-06'
        self.subscription.endDate = '1994-10-10'
        self.subscription.subscribed = True
        self.subscription.preferences = [{'key': 'key', 'value': 'value'}]

        self.subscription.put()
        mock_post.assert_called_with(self.base_url_customer + '/' + self.customer.id + '/subscriptions/01',
                                    headers=self.headers_expected, json=self.subscription.attributes)
        assert self.customer.base.subscriptions[0].attributes == self.subscription.attributes,  (self.customer.base.subscriptions[0].attributes,
                                                                               self.subscription.attributes)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_subscription_response'))
    def test_put_no_subscriptions(self, mock_post):
        self.subscription.name = 'name'
        self.subscription.type = 'type'
        self.subscription.kind = 'kind'
        self.subscription.subscriberId = 'subscriberId'
        self.subscription.startDate = '1994-10-06'
        self.subscription.endDate = '1994-10-10'
        self.subscription.subscribed = True
        self.subscription.preferences = [{'key': 'key', 'value': 'value'}]
        try:
            self.subscription.put()
        except ValueError as e:
            assert 'Subscription' in str(e)

    @mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_education_response'))
    def test_put_no(self, mock_post):
        self.customer.base.subscriptions = [self.subscription]
        subscription = Subscription(customer=self.customer, id='03')
        subscription.name = 'name'
        subscription.type = 'type'
        subscription.kind = 'kind'
        subscription.subscriberId = 'subscriberId'
        subscription.startDate = '1994-10-06'
        subscription.endDate = '1994-10-10'
        subscription.subscribed = True
        subscription.preferences = [{'key': 'key', 'value': 'value'}]
        try:
            subscription.put()
        except ValueError as e:
            assert 'Subscription' in str(e)