Skip to content

Commit

Permalink
Merge pull request #134 from avadev/SDK_bug_fixes
Browse files Browse the repository at this point in the history
MR : fixed AS-134 and AS-135
  • Loading branch information
svc-developer authored Sep 14, 2022
2 parents 864a482 + 03713e8 commit 0dd59dc
Show file tree
Hide file tree
Showing 8 changed files with 282 additions and 104 deletions.
3 changes: 2 additions & 1 deletion src/avalara/transaction_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,11 @@ def __init__(self, client, comp_code, type_, cust_code):
# Keeps track of line number when adding multiple lines
self.line_num = 1
# The in-progress model

self.create_model = {
'companyCode': comp_code,
'customerCode': cust_code,
'type': type_,
'date': '{}'.format(datetime.now()),
'lines': []
'lines': [],
}
80 changes: 55 additions & 25 deletions src/avalara/transaction_builder_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,22 @@ def with_latlong(self, address_type, lat, long_):
:return: TransactionBuilder
"""
self.create_model.setdefault('addresses', {})
self.create_model['addresses'][address_type] = {'latitude': float(lat),
'longitude': float(long_)}
self.create_model['addresses'][address_type] = {
'latitude': float(lat),
'longitude': float(long_),
}
return self

def with_line(self, amount, quantity, item_code, tax_code, line_number=None):
def with_line(
self,
amount,
quantity,
item_code,
tax_code="",
line_number=None,
tax_included=False,
exemption_code="",
):
r"""
Add a line to the transaction.
Expand All @@ -136,42 +147,58 @@ def with_line(self, amount, quantity, item_code, tax_code, line_number=None):
:param string item_code: Code of the item.
:param string tax_code: Tax Code of the item. If left blank, \
the default item (P0000000) is assumed.
:param [int] line_number: Value of the line number.
:param Any line_number: Value of the line number.
:param bool tax_included: Is line amount tax included, defaults \
to false
:param string exemption_code: exemption_code in case of exempt \
line, defaults to blank
:return: TransactionBuilder
"""
# fix for issue #133
# in case line number is set as string, use it as transaction line
# number and continue incrementing object level line number for other
# lines (with no line numbers)
txn_line_number = self.line_num
if line_number is not None:
self.line_num = line_number;

if isinstance(
line_number, (int, float, complex)
) and not isinstance(line_number, bool):
self.line_num = line_number
txn_line_number = self.line_num
else:
txn_line_number = line_number

temp = {
'number': str(self.line_num),
'number': str(txn_line_number),
'amount': amount,
'quantity': quantity,
'itemCode': str(item_code),
'taxCode': str(tax_code)
'taxCode': str(tax_code),
'taxIncluded': tax_included,
'exemptionCode': str(exemption_code),
}

self.create_model['lines'].append(temp)
self.line_num += 1
return self

def with_exempt_line(self, amount, item_code, exemption_code):
def with_exempt_line(self, amount, item_code, exemption_code, quantity=1):
"""
Add a line with an exemption to this transaction.
:param float amount: The amount of this line item
:param string item_code: The code for the item
:param string exemption_code: The exemption code for this line item
:param int quantity: quantity, defaults to 1
:return: TransactionBuilder
"""
self.with_line(
quantity=quantity,
item_code=item_code,
amount=amount,
exemption_code=exemption_code,
)

temp = {
'number': str(self.line_num),
'quantity': 1,
'amount': amount,
'exemptionCode': str(exemption_code),
'itemCode': str(item_code)
}
self.create_model['lines'].append(temp)
self.line_num += 1
return self

def with_diagnostics(self):
Expand Down Expand Up @@ -238,7 +265,12 @@ def get_most_recent_line(self, member_name=None):
"""
line = self.create_model['lines']
if not len(line): # if length is zero
raise Exception('No lines have been added. The {} method applies to the most recent line. To use this function, first add a line.'.format(member_name))
raise Exception(
'No lines have been added. The {} method applies to the most \
recent line. To use this function, first add a line.'.format(
member_name
)
)
return line[-1]

def create(self, include=None):
Expand Down Expand Up @@ -270,7 +302,7 @@ def with_line_tax_override(self, type_, reason, tax_amount, tax_date):
'type': str(type_),
'reason': str(reason),
'taxAmount': float(tax_amount),
'taxDate': tax_date
'taxDate': tax_date,
}
return self

Expand All @@ -293,7 +325,7 @@ def with_tax_override(self, type_, reason, tax_amount, tax_date):
'type': str(type_),
'reason': str(reason),
'taxAmount': tax_amount,
'taxDate': tax_date
'taxDate': tax_date,
}
return self

Expand Down Expand Up @@ -321,9 +353,7 @@ def with_separate_address_line(self, amount, type_, address):
'number': self.line_num,
'quantity': 1,
'amount': amount,
'addresses': {
type_: address
}
'addresses': {type_: address},
}

self.create_model['lines'].append(temp)
Expand All @@ -341,5 +371,5 @@ def create_adjustment_request(self, desc, reason):
return {
'newTransaction': self.create_model,
'adjustmentDescription': desc,
'adjustmentReason': reason
'adjustmentReason': reason,
}
Empty file added tests/__init__.py
Empty file.
104 changes: 68 additions & 36 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Conftest is a file recognize by pytest module, allowing us to share fixture across multiple tests."""
from avalara import AvataxClient
from avalara.transaction_builder import TransactionBuilder
from src.avalara import AvataxClient
from src.avalara.transaction_builder import TransactionBuilder
import os
import pytest

Expand Down Expand Up @@ -53,7 +53,7 @@ def ship_from_address():
'line1': '123 Main Street',
'city': 'Irvine',
'region': 'CA',
'postalCode': '92615'
'postalCode': '92615',
}
return address

Expand Down Expand Up @@ -95,29 +95,38 @@ def five_transactions():
('Poulsbo', '200 Moe St Ne', '98370', 'WA'),
('Los Angeles', '1945 S Hill St', '90007', 'CA'),
('Chicago', '50 W Washington St', '60602', 'IL'),
('Irvine', '123 Main Street', '92615', 'CA')
('Irvine', '123 Main Street', '92615', 'CA'),
]
for city, line1, postal, region in addresses:
tax_document = {
'addresses': {'SingleLocation': {'city': city,
'country': 'US',
'line1': line1,
'postalCode': postal,
'region': region}},
'addresses': {
'SingleLocation': {
'city': city,
'country': 'US',
'line1': line1,
'postalCode': postal,
'region': region,
}
},
'commit': False,
'companyCode': 'DEFAULT',
'currencyCode': 'USD',
'customerCode': 'ABC',
'date': '2017-04-12',
'description': 'Yarn',
'lines': [{'amount': 100,
'description': 'Yarn',
'itemCode': 'Y0001',
'number': '1',
'quantity': 1,
'taxCode': 'PS081282'}],
'lines': [
{
'amount': 100,
'description': 'Yarn',
'itemCode': 'Y0001',
'number': '1',
'quantity': 1,
'taxCode': 'PS081282',
}
],
'purchaseOrderNo': '2017-04-12-001',
'type': 'SalesInvoice'}
'type': 'SalesInvoice',
}
r = client.create_transaction(tax_document, None)
trans_codes.append(r.json()['code'])
return trans_codes
Expand All @@ -128,6 +137,7 @@ def tax_document():
"""Create a tax document dictionary."""
return default_trans_model()


@pytest.fixture(scope='function')
def init_comp_model():
"""Return the following initialize company model for company DEFAULT."""
Expand All @@ -145,41 +155,64 @@ def init_comp_model():
"title": "Owner",
"email": "[email protected]",
"phoneNumber": "714 555-2121",
"mobileNumber": "714 555-1212"}
"mobileNumber": "714 555-1212",
}


def cred_determine():
"""Return the appropriate pair of cred."""
if os.environ.get('USERNAME') and os.environ.get('PASSWORD'):
return (os.environ.get('USERNAME'), os.environ.get('PASSWORD'))
elif os.environ.get('SANDBOX_CLIENTID') and os.environ.get('SANDBOX_LICENSEKEY'):
return (os.environ.get('SANDBOX_CLIENTID'), os.environ.get('SANDBOX_LICENSEKEY'))
elif os.environ.get('SANDBOX_USERNAME') and os.environ.get('SANDBOX_PASSWORD'):
return (os.environ.get('SANDBOX_USERNAME'), os.environ.get('SANDBOX_PASSWORD'))
elif os.environ.get('SANDBOX_CLIENTID') and os.environ.get(
'SANDBOX_LICENSEKEY'
):
return (
os.environ.get('SANDBOX_CLIENTID'),
os.environ.get('SANDBOX_LICENSEKEY'),
)
elif os.environ.get('SANDBOX_USERNAME') and os.environ.get(
'SANDBOX_PASSWORD'
):
return (
os.environ.get('SANDBOX_USERNAME'),
os.environ.get('SANDBOX_PASSWORD'),
)
else:
raise ValueError()


def default_trans_model():
"""Return the default transaction model."""
return {
'addresses': {'SingleLocation': {'city': 'Irvine',
'country': 'US',
'line1': '123 Main Street',
'postalCode': '92615',
'region': 'CA'}},
'addresses': {
'SingleLocation': {
'city': 'Irvine',
'country': 'US',
'line1': '123 Main Street',
'postalCode': '92615',
'region': 'CA',
}
},
'commit': False,
'companyCode': 'DEFAULT',
'currencyCode': 'USD',
'customerCode': 'ABC',
'date': '2017-04-12',
'description': 'Yarn',
'lines': [{'amount': 100,
'description': 'Yarn',
'itemCode': 'Y0001',
'number': '1',
'quantity': 1,
'taxCode': 'PS081282'}],
'lines': [
{
'amount': 100,
'description': 'Yarn',
'itemCode': 'Y0001',
'number': '1',
'quantity': 1,
'taxCode': 'PS081282',
}
],
'purchaseOrderNo': '2017-04-12-001',
'type': 'SalesInvoice'}
'type': 'SalesInvoice',
}


def pytest_runtest_makereport(item, call):
"""For incremental testing fixture called mark.increment."""
Expand All @@ -188,11 +221,10 @@ def pytest_runtest_makereport(item, call):
parent = item.parent
parent._previousfailed = item


def pytest_runtest_setup(item):
"""For incremental testing fixture called mark.increment."""
if "incremental" in item.keywords:
previousfailed = getattr(item.parent, "_previousfailed", None)
if previousfailed is not None:
pytest.xfail("previous test failed (%s)" %previousfailed.name)


pytest.xfail("previous test failed (%s)" % previousfailed.name)
3 changes: 1 addition & 2 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Test the add_credential method."""
import pytest
from requests.auth import HTTPBasicAuth
from avalara.client import AvataxClient
from src.avalara.client import AvataxClient


def test_username_auth(unauth_client):
Expand Down Expand Up @@ -59,4 +59,3 @@ def test_no_auth_if_no_cred_is_added(unauth_client):
def test_if_valid_pair_sandbox_cred_in_place(auth_client):
"""Test if there is a pair of valid Avatax credentials stored in env."""
assert auth_client is not None

12 changes: 8 additions & 4 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Test the client model."""
from avalara.client import AvataxClient
from src.avalara.client import AvataxClient


def test_client_can_be_created(unauth_client):
Expand Down Expand Up @@ -29,7 +29,10 @@ def test_client_has_machine_name_attribute(unauth_client):

def test_that_client_id_is_created(unauth_client):
"""Test that the client id is created and properly formatted."""
assert unauth_client.client_id == 'test app; ver 0.0; Python SDK; 18.5; test machine;'
assert (
unauth_client.client_id
== 'test app; ver 0.0; Python SDK; 18.5; test machine;'
)


def test_client_can_obtain_production_url_as_base_url():
Expand All @@ -40,6 +43,7 @@ def test_client_can_obtain_production_url_as_base_url():

def test_client_can_obtain_their_own_base_url():
"""Test the client can input a url as the base url."""
client = AvataxClient('test app', 'ver 0.0', 'test machine', 'https://myurl.com')
client = AvataxClient(
'test app', 'ver 0.0', 'test machine', 'https://myurl.com'
)
assert client.base_url == 'https://myurl.com'

5 changes: 3 additions & 2 deletions tests/test_create_trans.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ def test_transaction_is_saved_when_commit_is_false(auth_client, tax_document):
assert '"status":"Saved"' in r.text


def test_transaction_is_commited_when_commit_is_true(auth_client, tax_document):
def test_transaction_is_commited_when_commit_is_true(
auth_client, tax_document
):
"""Test that a transaction is commited when commit is true."""
tax_document['commit'] = True
r = auth_client.create_transaction(tax_document, None)
Expand All @@ -41,4 +43,3 @@ def test_include_param_is_addresses(auth_client, tax_document):
include = {'$include': 'Addresses'}
r = auth_client.create_transaction(tax_document, include)
assert 'addresses' in r.text

Loading

0 comments on commit 0dd59dc

Please sign in to comment.