예제 #1
0
    def test__authenticate(self):
        failed_request = mock.Mock(
            **{
                "status_code": 401,
                "json.return_value": {
                    "TransactionResult": {
                        "SeverityText": "Warning",
                        "ResultID": "SC001",
                        "ResultText": "Invalid Credentials",
                        "ResultMessage": {
                            "ResultDescription": "Your user credentials are invalid. Please contact "
                            "your D&B Representative or your local Customer "
                            "Service Center."
                        },
                    },
                    "TransactionDetail": {
                        "ApplicationTransactionID": "",
                        "ServiceTransactionID": "Id-2aff06563f327800e6661f003aac2627",
                        "TransactionTimestamp": "2015-09-26T16:25:14.193",
                    },
                },
            }
        )

        success_request = mock.Mock(
            **{
                "status_code": 200,
                "json.return_value": {
                    "TransactionResult": {
                        "SeverityText": "Information",
                        "ResultID": "CM000",
                        "ResultText": "Success",
                        "ResultMessage": {"ResultDescription": "Success"},
                    },
                    "AuthenticationDetail": {"Token": self.auth_token},
                    "TransactionDetail": {
                        "ApplicationTransactionID": "",
                        "ServiceTransactionID": "Id-6e0007569042780011671f00ca2011db",
                        "TransactionTimestamp": "2015-09-26T16:30:38.160",
                    },
                },
            }
        )

        with mock.patch("dnb_direct.client.requests") as requests_mock:

            # Failed auth
            requests_mock.post.return_value = failed_request
            client = DirectClient("foo", "bar")
            self.assertRaises(DnbAuthenticationError, lambda: client._authenticate())

            # Successful auth
            requests_mock.post.return_value = success_request
            client = DirectClient("foo", "bar")
            self.assertEqual(client._authenticate(), self.auth_token)
            requests_mock.post.assert_called_with(
                "https://maxcvservices.dnb.com/Authentication/V2.0/", headers={"x-dnb-user": "******", "x-dnb-pwd": "bar"}
            )
예제 #2
0
    def setUp(self):
        self.auth_token = 'FduimCvtEvqkGd6mkrYVWNdNibe3XcmXZKBGf9InmIzjC4I3Ljl0842LmFBOM5vfhb269' \
                          'gYAsxG/U7hSKZtzLUAufkswGu7lF2/kfGYd+AMjV5ftn7NCclrnB9or6a8Zsz3HyPyNXW' \
                          'JSH2zhbH+CydyTsZJjDxMsG4Mkon/S1I8E1A1rRvBxOkTYHI2qdCQGgjf9i9A/cuNe1qv' \
                          '6m2t/egdciRlZ7EQNM8dR8URJntHXvxQMY379dbHVCaBnZGGFCFHsEj0ilGTBS2y0bbj7' \
                          'KsooC+UmjRqXeHA3lh4KKVfe9Z8rYYV+0W9ovI7XyJykFP/8H2d+6xIHjyF8xMjZwuNo+' \
                          'NNbSpw4mvfacNigAso='

        self.failed_request = mock.Mock(**{
            'status_code': 200,
            'json.return_value': {
                "ServiceError": {
                    "TransactionDetail": {
                        "ApplicationTransactionID": "REST",
                        "ServiceTransactionID": "Id-6e040756527b7800a2671f00e043d181",
                        "TransactionTimestamp": "2015-09-26T16:47:42"
                    },
                    "TransactionResult": {
                        "SeverityText": "Error",
                        "ResultID": "CM002",
                        "ResultText": "Invalid URL provided"
                    }
                }
            },
        })

        self.success_request = mock.Mock(**{
            'status_code': 200,
            'json.return_value': {'MatchResponse': {
                'TransactionDetail':
                   {'ServiceTransactionID': 'Id-a5d9ad5583e20000b5440500292a0073-1',
                    'TransactionTimestamp': '2015-07-21T01:33:25'},
                'TransactionResult':
                   {'ResultText': 'Success', 'ResultID': 'CM000', 'SeverityText': 'Information'},
                '@ServiceVersionNumber': '5.0',
                'MatchResponseDetail':
                   {'MatchCandidate': [{'OrganizationPrimaryName': {'OrganizationName': {'$': 'Studio Staalkaart'}}, 'MailingAddress': {'CountryISOAlpha2Code': 'NL', 'UndeliverableIndicator': False}, 'OperatingStatusText': {'$': 'Active'}, 'MatchQualityInformation': {'MatchGradeText': 'ZZZZZZZZZAZ', 'MatchDataProfileComponent': [{'MatchDataProfileComponentTypeText': {'$': 'Name'}, 'MatchDataProfileComponentValue': '20'}, {'MatchDataProfileComponentTypeText': {'$': 'Street Number'}, 'MatchDataProfileComponentValue': '99'}, {'MatchDataProfileComponentTypeText': {'$': 'Street Name'}, 'MatchDataProfileComponentValue': '99'}, {'MatchDataProfileComponentTypeText': {'$': 'City'}, 'MatchDataProfileComponentValue': '99'}, {'MatchDataProfileComponentTypeText': {'$': 'State'}, 'MatchDataProfileComponentValue': '98'}, {'MatchDataProfileComponentTypeText': {'$': 'PO Box'}, 'MatchDataProfileComponentValue': '99'}, {'MatchDataProfileComponentTypeText': {'$': 'Phone'}, 'MatchDataProfileComponentValue': '98'}, {'MatchDataProfileComponentTypeText': {'$': 'Postal Code'}, 'MatchDataProfileComponentValue': '99'}, {'MatchDataProfileComponentTypeText': {'$': 'DUNS'}, 'MatchDataProfileComponentValue': '00'}, {'MatchDataProfileComponentTypeText': {'$': 'SIC'}, 'MatchDataProfileComponentValue': '00'}, {'MatchDataProfileComponentTypeText': {'$': 'Density'}, 'MatchDataProfileComponentValue': '98'}, {'MatchDataProfileComponentTypeText': {'$': 'Uniqueness'}, 'MatchDataProfileComponentValue': '00'}, {'MatchDataProfileComponentTypeText': {'$': 'National ID'}, 'MatchDataProfileComponentValue': '98'}, {'MatchDataProfileComponentTypeText': {'$': 'URL'}, 'MatchDataProfileComponentValue': '98'}], 'MatchDataProfileText': '2099999998999899000098009898', 'ConfidenceCodeValue': 10, 'MatchDataProfileComponentCount': 14, 'MatchGradeComponentCount': 10, 'MatchGradeComponent': [{'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Name'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Street Number'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Street Name'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'City'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'PO Box'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Phone'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Postal Code'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Density'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Uniqueness'}, 'MatchGradeComponentRating': 'A'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Sic'}, 'MatchGradeComponentRating': 'Z'}]}, 'PrimaryAddress': {'StreetAddressLine': [{'LineText': 'E M Beimastrjitte 56-58'}], 'CountryISOAlpha2Code': 'NL', 'UndeliverableIndicator': False, 'PrimaryTownName': 'Eastermar', 'PostalCode': '9261 VK'}, 'TelephoneNumber': {'TelecommunicationNumber': '1234567890', 'UnreachableIndicator': False}, 'DisplaySequence': 1, 'DUNSNumber': '1234567890', 'OrganizationIdentificationNumberDetail': {'@DNBCodeValue': 23097, 'OrganizationIdentificationNumber': '123456AAAA11', '@TypeText': 'RSIN', '@DNBCodeTableNumber': 7}, 'StandaloneOrganizationIndicator': True}], 'InquiryReferenceDetail': {'CustomerReferenceText': ['Sample'], 'CustomerBillingEndorsementText': 'Sample'}, 'MatchDataCriteriaText': {'$': 'National ID Lookup'}, 'CandidateMatchedQuantity': 1}
            }},
        })

        self.client = DirectClient('foo', 'bar')
        self.client._authenticate = mock.Mock(return_value='somevalidtoken')
        self.client.call_api = mock.Mock()
    def setUp(self):
        self.auth_token = 'FduimCvtEvqkGd6mkrYVWNdNibe3XcmXZKBGf9InmIzjC4I3Ljl0842LmFBOM5vfhb269' \
                          'gYAsxG/U7hSKZtzLUAufkswGu7lF2/kfGYd+AMjV5ftn7NCclrnB9or6a8Zsz3HyPyNXW' \
                          'JSH2zhbH+CydyTsZJjDxMsG4Mkon/S1I8E1A1rRvBxOkTYHI2qdCQGgjf9i9A/cuNe1qv' \
                          '6m2t/egdciRlZ7EQNM8dR8URJntHXvxQMY379dbHVCaBnZGGFCFHsEj0ilGTBS2y0bbj7' \
                          'KsooC+UmjRqXeHA3lh4KKVfe9Z8rYYV+0W9ovI7XyJykFP/8H2d+6xIHjyF8xMjZwuNo+' \
                          'NNbSpw4mvfacNigAso='
        
        self.success_request = mock.Mock(**{
            'status_code': 200,
            'json.return_value': {'OrderProductResponse': {
                'TransactionDetail': {'ServiceTransactionID': 'Id-4acb0e5680e5d3007ca220002b5f6d11-2', 'TransactionTimestamp': '2015-10-02T14:22:03.537-04:00'},
                '@ServiceVersionNumber': '5.1',
                'OrderProductResponseDetail': {'InquiryDetail': {'CountryISOAlpha2Code': 'US', 'DUNSNumber': '804735132'},'Product': {'Organization': {'Location': {'MailingAddress': [{'CountryISOAlpha2Code': 'US', 'UndeliverableIndicator': False}], 'PrimaryAddress': [{'PremisesUsageDetail': [{'PremisesUsageFunctionDetail': [{'PremisesFunctionText': {'$': 'Manufacturing', '@DNBCodeValue': 12058}}]}], 'RegisteredAddressIndicator': False, 'GeographicalPrecisionText': {'$': 'Unknown', '@DNBCodeValue': 0}, 'CountyOfficialName': 'San Francisco County', 'UndeliverableIndicator': False, 'MetropolitanStatisticalAreaUSCensusCode': ['San Francisco-Oakland-Hayward CA'], 'AddressUsageTenureDetail': [{'TenureTypeText': {'$': 'Rents', '@DNBCodeValue': 1129}}], 'StreetAddressLine': [{'LineText': '492 KOLLER ST'}], 'PrimaryTownName': 'San Francisco', 'TerritoryOfficialName': 'California', 'TerritoryAbbreviatedName': 'CA', 'CountryGroupName': 'North America', 'CountryISOAlpha2Code': 'US', 'PostalCode': '94110', 'ResidentialAddressIndicator': False}]}, 'Assessment': {'CommercialCreditScore': [{'MarketingRiskClassText': {'$': 'Low', '@DNBCodeValue': 10925}}], 'HistoryRatingText': {'$': 'CLEAR', '@DNBCodeValue': 9078}}, 'SocioEconomicIdentification': {'MinorityOwnedIndicator': False, 'SmallBusinessIndicator': True, 'OwnershipEthnicity': [{'EthnicityTypeText': {'$': 'Unknown', '@DNBCodeValue': 0}}], 'LaborSurplusAreaIndicator': False, 'FemaleOwnedIndicator': False}, 'OrganizationName': {'OrganizationPrimaryName': [{'OrganizationName': {'$': 'Gorman Manufacturing Company, Inc.'}}]}, 'PrincipalsAndManagement': {'CurrentPrincipal': [{'CurrentManagementResponsibility': [{'ManagementResponsibilityText': {'$': 'Secretary', '@ManagementResponsibilityCode': 'A1B2'}}], 'PrincipalIdentificationNumberDetail': [{'@TypeText': 'Professional Contact Identifier', '@DNBCodeValue': 24215, 'PrincipalIdentificationNumber': '220656221'}], 'JobTitle': [{'JobTitleText': {'$': 'Sec-treas'}}], 'PrincipalName': {'MiddleName': 'J', 'FullName': 'Kevin J Hunt', 'FirstName': 'Kevin', 'NamePrefix': {'NamePrefixText': 'Mr'}, '@type': 'fir:IndividualNameType', 'LastName': 'Hunt'}}, {'CurrentManagementResponsibility': [{'ManagementResponsibilityText': {'$': 'President', '@ManagementResponsibilityCode': 'A1A6'}}], 'PrincipalIdentificationNumberDetail': [{'@TypeText': 'Professional Contact Identifier', '@DNBCodeValue': 24215, 'PrincipalIdentificationNumber': '5412657'}], 'JobTitle': [{'JobTitleText': {'$': 'Pres'}}], 'PrincipalName': {'LastName': 'Smith', '@type': 'fir:IndividualNameType', 'FullName': 'Leslie Smith', 'FirstName': 'Leslie'}}]}, 'OrganizationDetail': {'FamilyTreeMemberRole': [{'FamilyTreeMemberRoleText': {'$': 'Global Ultimate', '@DNBCodeValue': 12775}}, {'FamilyTreeMemberRoleText': {'$': 'Domestic Ultimate', '@DNBCodeValue': 12774}}, {'FamilyTreeMemberRoleText': {'$': 'Parent', '@DNBCodeValue': 12773}}, {'FamilyTreeMemberRoleText': {'$': 'Headquarters', '@DNBCodeValue': 12771}}], 'BoneyardOrganizationIndicator': False, 'ControlOwnershipTypeText': {'$': 'Unknown', '@DNBCodeValue': 0}, 'OrganizationStartYear': '1985', 'StandaloneOrganizationIndicator': False, 'ControlOwnershipDate': {'$': '1985'}, 'OperatingStatusText': {'$': 'Active', '@DNBCodeValue': 9074}}, 'IndustryCode': {'IndustryCode': [{'@TypeText': 'D&B Hoovers Industry Code', '@DNBCodeValue': 25838, 'IndustryCodeDescription': [{'$': 'Commercial Printing', '@IndustryCodeDescriptionLengthCode': 9120, '@LanguageCode': 39}], 'IndustryCode': {'$': '1068'}, 'DisplaySequence': 1}, {'@TypeText': 'NAICS', '@DNBCodeValue': 700, 'IndustryCodeDescription': [{'$': 'Commercial Gravure Printing', '@IndustryCodeDescriptionLengthCode': 9120, '@LanguageCode': 39}], 'IndustryCode': {'$': '323111'}, 'DisplaySequence': 1}, {'@TypeText': 'UK SIC 2003', '@DNBCodeValue': 21182, 'IndustryCodeDescription': [{'$': 'Other printing', '@IndustryCodeDescriptionLengthCode': 9120, '@LanguageCode': 39}], 'IndustryCode': {'$': '22.220'}, 'DisplaySequence': 1}, {'@TypeText': 'D&B Standard Industry Code', '@DNBCodeValue': 3599, 'IndustryCodeDescription': [{'$': 'COMM PRTG  LITHO', '@IndustryCodeDescriptionLengthCode': 2121, '@LanguageCode': 39}], 'IndustryCode': {'$': '27520000'}, 'DisplaySequence': 1}, {'@TypeText': 'US Standard Industry Code 1987 - 4 digit', 'IndustryCodeDescription': [{'$': 'Lithographic commercial printing', '@IndustryCodeDescriptionLengthCode': 1441, '@LanguageCode': 39}], 'IndustryCode': {'$': '2752'}, 'SalesPercentage': 100, '@DNBCodeValue': 399, 'DisplaySequence': 1}]}, 'SubjectHeader': {'DUNSSelfRequestIndicator': False, 'LastUpdateDate': {'$': '2015-02-03'}, 'OrganizationSummaryText': 'Commercial printing, lithographic', 'NonMarketableReasonText': [{'$': 'De-listed', '@DNBCodeValue': 11028}, {'$': 'Insufficient Data', '@DNBCodeValue': 25837}], 'MarketabilityIndicator': False, 'TransferDUNSNumberRegistration': [{'TransferredFromDUNSNumber': '030718519'}], 'DUNSNumber': '804735132', 'TotalInquiriesCount': 0}, 'Financial': {'KeyFinancialFiguresOverview': [{'StatementHeaderDetails': {'FinancialStatementToDate': {'$': '2014-12-31'}, 'FinancialPeriodDuration': 'P1Y'}, 'SalesRevenueAmount': [{'$': 20839372, '@CurrencyISOAlpha3Code': 'USD', '@ReliabilityText': 'Actual', '@UnitOfSize': 'SingleUnits'}, {'$': 20839372, '@CurrencyISOAlpha3Code': 'USD', '@ReliabilityText': 'Actual', '@UnitOfSize': 'SingleUnits'}]}]}, 'EmployeeFigures': {'IndividualEntityEmployeeDetails': {'TotalEmployeeQuantity': 110, 'ReliabilityText': {'$': 'Actual', '@DNBCodeValue': 9092}}, 'ConsolidatedEmployeeDetails': {'EmployeeCategoryDetails': [{'EmployeeBasisText': {'$': 'Principals', '@DNBCodeValue': 9064}}], 'TotalEmployeeQuantity': 125, 'ReliabilityText': {'$': 'Actual', '@DNBCodeValue': 9092}}}, 'Telecommunication': {'TelephoneNumber': [{'UnreachableIndicator': False, 'InternationalDialingCode': '1', 'TelecommunicationNumber': '06505550000'}]}, 'RegisteredDetail': {'LegalFormDetails': {'LegalFormText': {'$': 'Corporation', '@DNBCodeValue': 451}}, 'IncorporationYear': '1985', 'OrganizationIdentificationNumberDetail': [{'@TypeText': 'Federal Taxpayer Identification Number (US)', 'AssignmentMethodText': 'Direct Source', 'RegistrationIssuerDUNSNumber': '137375200', 'PreferredOrganizationIdentificationNumberIndicator': True, 'RegistrationIssuerName': 'D&B', 'RegistrationLocation': {'PrimaryAddress': [{'PrimaryTownName': 'SAN FRANCISCO', 'StreetAddressLine': [{'LineText': '492 KOLLER STREET'}], 'PostalCode': '94110', 'TerritoryName': 'CA'}]}, '@DNBCodeValue': 6863, 'StartDate': {'$': '2008-04-28'}, 'OrganizationIdentificationNumber': '123456789', 'FilingOrganizationName': 'GORMAN MANUFACTURING COMPANY, INC'}]}, 'Linkage': {'GlobalUltimateOrganization': {'OrganizationPrimaryName': [{'OrganizationName': {'$': 'GORMAN MANUFACTURING COMPANY, INC.'}}], 'PrimaryAddress': [{'PrimaryTownName': 'SAN FRANCISCO', 'TerritoryOfficialName': 'California', 'TerritoryAbbreviatedName': 'CA', 'PostalCode': '94110', 'CountryISOAlpha2Code': 'US', 'StreetAddressLine': [{'LineText': '492 KOLLER ST'}]}], 'DUNSNumber': '804735132'}, 'LinkageSummary': {'GlobalUltimateFamilyTreeLinkageCount': 8}, 'DomesticUltimateOrganization': {'OrganizationPrimaryName': [{'OrganizationName': {'$': 'GORMAN MANUFACTURING COMPANY, INC.'}}], 'PrimaryAddress': [{'PrimaryTownName': 'SAN FRANCISCO', 'TerritoryOfficialName': 'California', 'TerritoryAbbreviatedName': 'CA', 'PostalCode': '94110', 'CountryISOAlpha2Code': 'US', 'StreetAddressLine': [{'LineText': '492 KOLLER ST'}]}], 'DUNSNumber': '804735132'}}, 'ActivitiesAndOperations': {'PrimarySICCategoryValue': 'D', 'LineOfBusinessDetails': [{'LineOfBusinessDescription': {'$': 'Commercial printing, lithographic'}}]}}, 'DNBProductID': 'DCP_PREM'}},
                'TransactionResult': {'ResultID': 'CM000', 'SeverityText': 'Information', 'ResultText': 'Success'}
            }}
,
        })

        self.client = DirectClient('foo', 'bar')
        self.client._authenticate = mock.Mock(return_value='somevalidtoken')
        self.client.call_api = mock.Mock()
예제 #4
0
class DirectClientMatchTestCase(TestCase):
    """
    Tests for the match endpoint of the DNB Direct API
    """

    def setUp(self):
        self.auth_token = 'FduimCvtEvqkGd6mkrYVWNdNibe3XcmXZKBGf9InmIzjC4I3Ljl0842LmFBOM5vfhb269' \
                          'gYAsxG/U7hSKZtzLUAufkswGu7lF2/kfGYd+AMjV5ftn7NCclrnB9or6a8Zsz3HyPyNXW' \
                          'JSH2zhbH+CydyTsZJjDxMsG4Mkon/S1I8E1A1rRvBxOkTYHI2qdCQGgjf9i9A/cuNe1qv' \
                          '6m2t/egdciRlZ7EQNM8dR8URJntHXvxQMY379dbHVCaBnZGGFCFHsEj0ilGTBS2y0bbj7' \
                          'KsooC+UmjRqXeHA3lh4KKVfe9Z8rYYV+0W9ovI7XyJykFP/8H2d+6xIHjyF8xMjZwuNo+' \
                          'NNbSpw4mvfacNigAso='

        self.failed_request = mock.Mock(**{
            'status_code': 200,
            'json.return_value': {
                "ServiceError": {
                    "TransactionDetail": {
                        "ApplicationTransactionID": "REST",
                        "ServiceTransactionID": "Id-6e040756527b7800a2671f00e043d181",
                        "TransactionTimestamp": "2015-09-26T16:47:42"
                    },
                    "TransactionResult": {
                        "SeverityText": "Error",
                        "ResultID": "CM002",
                        "ResultText": "Invalid URL provided"
                    }
                }
            },
        })

        self.success_request = mock.Mock(**{
            'status_code': 200,
            'json.return_value': {'MatchResponse': {
                'TransactionDetail':
                   {'ServiceTransactionID': 'Id-a5d9ad5583e20000b5440500292a0073-1',
                    'TransactionTimestamp': '2015-07-21T01:33:25'},
                'TransactionResult':
                   {'ResultText': 'Success', 'ResultID': 'CM000', 'SeverityText': 'Information'},
                '@ServiceVersionNumber': '5.0',
                'MatchResponseDetail':
                   {'MatchCandidate': [{'OrganizationPrimaryName': {'OrganizationName': {'$': 'Studio Staalkaart'}}, 'MailingAddress': {'CountryISOAlpha2Code': 'NL', 'UndeliverableIndicator': False}, 'OperatingStatusText': {'$': 'Active'}, 'MatchQualityInformation': {'MatchGradeText': 'ZZZZZZZZZAZ', 'MatchDataProfileComponent': [{'MatchDataProfileComponentTypeText': {'$': 'Name'}, 'MatchDataProfileComponentValue': '20'}, {'MatchDataProfileComponentTypeText': {'$': 'Street Number'}, 'MatchDataProfileComponentValue': '99'}, {'MatchDataProfileComponentTypeText': {'$': 'Street Name'}, 'MatchDataProfileComponentValue': '99'}, {'MatchDataProfileComponentTypeText': {'$': 'City'}, 'MatchDataProfileComponentValue': '99'}, {'MatchDataProfileComponentTypeText': {'$': 'State'}, 'MatchDataProfileComponentValue': '98'}, {'MatchDataProfileComponentTypeText': {'$': 'PO Box'}, 'MatchDataProfileComponentValue': '99'}, {'MatchDataProfileComponentTypeText': {'$': 'Phone'}, 'MatchDataProfileComponentValue': '98'}, {'MatchDataProfileComponentTypeText': {'$': 'Postal Code'}, 'MatchDataProfileComponentValue': '99'}, {'MatchDataProfileComponentTypeText': {'$': 'DUNS'}, 'MatchDataProfileComponentValue': '00'}, {'MatchDataProfileComponentTypeText': {'$': 'SIC'}, 'MatchDataProfileComponentValue': '00'}, {'MatchDataProfileComponentTypeText': {'$': 'Density'}, 'MatchDataProfileComponentValue': '98'}, {'MatchDataProfileComponentTypeText': {'$': 'Uniqueness'}, 'MatchDataProfileComponentValue': '00'}, {'MatchDataProfileComponentTypeText': {'$': 'National ID'}, 'MatchDataProfileComponentValue': '98'}, {'MatchDataProfileComponentTypeText': {'$': 'URL'}, 'MatchDataProfileComponentValue': '98'}], 'MatchDataProfileText': '2099999998999899000098009898', 'ConfidenceCodeValue': 10, 'MatchDataProfileComponentCount': 14, 'MatchGradeComponentCount': 10, 'MatchGradeComponent': [{'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Name'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Street Number'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Street Name'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'City'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'PO Box'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Phone'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Postal Code'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Density'}, 'MatchGradeComponentRating': 'Z'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Uniqueness'}, 'MatchGradeComponentRating': 'A'}, {'MatchGradeComponentScore': 0, 'MatchGradeComponentTypeText': {'$': 'Sic'}, 'MatchGradeComponentRating': 'Z'}]}, 'PrimaryAddress': {'StreetAddressLine': [{'LineText': 'E M Beimastrjitte 56-58'}], 'CountryISOAlpha2Code': 'NL', 'UndeliverableIndicator': False, 'PrimaryTownName': 'Eastermar', 'PostalCode': '9261 VK'}, 'TelephoneNumber': {'TelecommunicationNumber': '1234567890', 'UnreachableIndicator': False}, 'DisplaySequence': 1, 'DUNSNumber': '1234567890', 'OrganizationIdentificationNumberDetail': {'@DNBCodeValue': 23097, 'OrganizationIdentificationNumber': '123456AAAA11', '@TypeText': 'RSIN', '@DNBCodeTableNumber': 7}, 'StandaloneOrganizationIndicator': True}], 'InquiryReferenceDetail': {'CustomerReferenceText': ['Sample'], 'CustomerBillingEndorsementText': 'Sample'}, 'MatchDataCriteriaText': {'$': 'National ID Lookup'}, 'CandidateMatchedQuantity': 1}
            }},
        })

        self.client = DirectClient('foo', 'bar')
        self.client._authenticate = mock.Mock(return_value='somevalidtoken')
        self.client.call_api = mock.Mock()

    def test_match_unexpected_args(self):
        self.client.call_api.return_value = self.failed_request
        self.assertRaises(TypeError, lambda: self.client.match(FooArg="test"))

    def test_match_street_line(self):
        self.client.call_api.return_value = self.failed_request
        # Too many street address lines
        self.assertRaises(DnbError, lambda: self.client.match(StreetAddressLine=['a', 'b', 'c']))

        # Correct number
        self.client.match(StreetAddressLine=['a', 'b'])
        self.client.call_api.assert_has_calls([
            mock.call('organizations', '5.0',
                      **{'StreetAddressLine-1': 'a', 'StreetAddressLine-2': 'b', 'match': 'true'})
        ])

        # Or zero
        self.client.match(StreetAddressLine=[])
        self.client.call_api.assert_has_calls([
            mock.call('organizations', '5.0',
                      **{'match': 'true'})
        ])

    def test_match_exclusion_criteria(self):

        self.client.call_api.return_value = self.failed_request
        # Too many street address lines
        self.assertRaises(DnbError, lambda: self.client.match(ExclusionCriteria=range(7)))

        # Correct number
        self.client.match(ExclusionCriteria=range(6))
        self.client.call_api.assert_has_calls([
            mock.call('organizations', '5.0',
                      **{'ExclusionCriteria-1': 0,
                         'ExclusionCriteria-2': 1,
                         'ExclusionCriteria-3': 2,
                         'ExclusionCriteria-4': 3,
                         'ExclusionCriteria-5': 4,
                         'ExclusionCriteria-6': 5,
                         'match': 'true'})
        ])

        # Or zero
        self.client.match(ExclusionCriteria=[])
        self.client.call_api.assert_has_calls([
            mock.call('organizations', '5.0',
                      **{'match': 'true'})
        ])

    def test_match_success(self):
        self.client.call_api.return_value = self.success_request

        now = datetime.datetime.now()

        self.client.match(ApplicationTransactionID="test", TransactionTimestamp=now,
              SubmittingOfficeID="1234", DUNSNumber="12345678", SubjectName="TestCompany",
              StreetAddressLine=["123 East Main", "Unit #1000"], PrimaryTownName="Seattle",
              CountryISOAlpha2Code="US", TerritoryName="WA", FullPostalCode="012345",
              TelephoneNumber="1234567890", InternationalDialingCode="1",
              OrganizationIdentificationNumber=123456, CandidateMaximumQuantity=1,
              ConfidenceLowerLevelThresholdValue=90, ExclusionCriteria=['a', 'b'],
              OrderReasonCode=None, MatchTypeText="Basic", CustomerReferenceText=None,
            CustomerBillingEndorsementText=None)

        self.client.call_api.assert_has_calls([
            mock.call('organizations', '5.0', **{
                'match': 'true',
                'ApplicationTransactionID': "test", 'TransactionTimestamp': now,
                'SubmittingOfficeID': "1234", 'DUNSNumber': "12345678", 'SubjectName':
                "TestCompany", 'StreetAddressLine-1': "123 East Main",
                'StreetAddressLine-2': "Unit #1000", 'PrimaryTownName': "Seattle",
                'CountryISOAlpha2Code': "US", 'TerritoryName': "WA", 'FullPostalCode': "012345",
                'TelephoneNumber': "1234567890", 'InternationalDialingCode': "1",
                'OrganizationIdentificationNumber': 123456, 'CandidateMaximumQuantity': 1,
                'ConfidenceLowerLevelThresholdValue': 90, 'ExclusionCriteria-1': 'a',
                'ExclusionCriteria-2': 'b', 'MatchTypeText': "Basic"
            })
        ])
예제 #5
0
    def test_call_api(self):

        failed_request = mock.Mock(
            **{
                "status_code": 200,
                "json.return_value": {
                    "ServiceError": {
                        "TransactionDetail": {
                            "ApplicationTransactionID": "REST",
                            "ServiceTransactionID": "Id-6e040756527b7800a2671f00e043d181",
                            "TransactionTimestamp": "2015-09-26T16:47:42",
                        },
                        "TransactionResult": {
                            "SeverityText": "Error",
                            "ResultID": "CM002",
                            "ResultText": "Invalid URL provided",
                        },
                    }
                },
            }
        )

        bad_endpoint_request = mock.Mock(**{"status_code": 200, "json.side_effect": ValueError})

        success_request = mock.Mock(
            **{
                "status_code": 200,
                "json.return_value": {
                    "MatchResponse": {
                        "TransactionDetail": {
                            "ServiceTransactionID": "Id-871d21a751de8134079b2d0c-1",
                            "TransactionTimestamp": "2013-07-11T05:56:05",
                        },
                        "TransactionResult": {
                            "SeverityText": "Information",
                            "ResultID": "CM000",
                            "ResultText": "Success",
                        },
                        "MatchResponseDetail": {
                            "MatchDataCriteriaText": {"$": "Name and Address Lookup"},
                            "CandidateMatchedQuantity": 24,
                            "MatchCandidate": [
                                {
                                    "DUNSNumber": "804735132",
                                    "OrganizationPrimaryName": {
                                        "OrganizationName": {"$": "GORMAN MANUFACTURING COMPANY, INC."}
                                    },
                                    "PrimaryAddress": {
                                        "StreetAddressLine": [{"LineText": "492 KOLLER STREET"}],
                                        "PrimaryTownName": "SAN FRANCISCO",
                                        "CountryISOAlpha2Code": "US",
                                        "PostalCode": "94110",
                                        "TerritoryAbbreviatedName": "CA",
                                        "UndeliverableIndicator": False,
                                    },
                                    "MailingAddress": {"CountryISOAlpha2Code": "US", "UndeliverableIndicator": False},
                                }
                            ],
                        },
                        "DisplaySequence": 24,
                    }
                },
            }
        )

        with mock.patch("dnb_direct.client.requests") as requests_mock:
            c = DirectClient("foo", "bar")
            c._authenticate = mock.Mock(return_value="somevalidtoken")

            # bad endpoint
            requests_mock.get.return_value = bad_endpoint_request
            self.assertRaises(DnbError, lambda: c.call_api("bad_endpoint"))

            # failed request
            requests_mock.get.return_value = failed_request
            response = c.call_api("organizations")
            self.assertEqual(response["ServiceError"]["TransactionResult"]["SeverityText"], "Error")

            # good request (GET)
            requests_mock.get.return_value = success_request
            params = {"SubjectName": "GORMAN MANUFACTURING", "match": "true"}
            c.call_api("organizations", "5.0", **params)
            requests_mock.get.assert_called_with(
                "https://maxcvservices.dnb.com/V5.0/organizations",
                headers={"Authorization": "somevalidtoken"},
                params=params,
            )