# Unit Test 真D好讚
# 🚀🚀🚀
###### tags: `ESUN`
speaker: **yc.chen**
---
## 沒資料 - 想做事 - Unit Test
```python=
class TestIPOLockupRule:
def test_try_change(self):
df = pd.DataFrame({
'bound_type': ['up', 'up', 'fx'],
'lower_bound': [0.0, 0.0, 0.1],
'upper_bound': [0.2, 0.2, 0.1],
'weight': [0.2, 0.2, 0.2],
'lockup_holding': ['N', 'Y', 'Y']
})
expected_var_dict_value = [
{'bound_type': 'up', 'lower_bound': 0.0, 'upper_bound': 0.2},
{'bound_type': 'fx', 'lower_bound': 0.2, 'upper_bound': 0.2},
{'bound_type': 'fx', 'lower_bound': 0.1, 'upper_bound': 0.1},
]
for idx, row in df.iterrows():
var_dict = {
'bound_type': BoundTypeVariable(row['bound_type']),
'lower_bound': LowerBoundVariable(row['lower_bound']),
'upper_bound': UpperBoundVariable(row['upper_bound']),
}
rule = IPOLockupRule()
rule.try_change(var_dict, row)
assert {col: var.value for col, var in var_dict.items()} == expected_var_dict_value[idx]
```
---
## 寫函數 - 不放心 - Unit Test
```python=
@pytest.mark.parametrize(
'sentence, expected_tokens, expected_text2token, expected_token2text',
[
(
'我 愛 喝 apple juice ',
['我', '愛', '喝', 'apple', 'j', '##ui', '##ce'],
[0, None, 1, None, None, 2, None, None, 3, 3, 3, 3, 3, None, 4, 5, 5, 6, 6, None],
[(0, 1), (2, 3), (5, 6), (8, 13), (14, 15), (15, 17), (17, 19)]
),
(
'Rolling in the deep ! !',
['rolling', 'in', 'the', 'deep', '!', '!'],
[0, 0, 0, 0, 0, 0, 0, None, 1, 1, None, 2, 2, 2, None, 3, 3, 3, 3, None, 4, None, 5],
[(0, 7), (8, 10), (11, 14), (15, 19), (20, 21), (22, 23)]
),
(
'I am YC.',
['i', 'am', 'y', '##c', '.'],
[0, None, 1, 1, None, 2, 3, 4],
[(0, 1), (2, 4), (5, 6), (6, 7), (7, 8)]
),
(
'未知:? unknown: ?',
['未', '知', ':', '[UNK]', 'u', '##nk', '##now', '##n', ':', '[UNK]'],
[0, 1, 2, 3, None, 4, 5, 5, 6, 6, 6, 7, 8, None, 9],
[(0, 1), (1, 2), (2, 3), (3, 4), (5, 6), (6, 8), (8, 11), (11, 12), (12, 13), (14, 15)]
)
]
)
def test_tokenize_and_map(sentence, expected_tokens, expected_text2token, expected_token2text):
def tokenize(word):
mapping = {
'juice': ['j', '##ui', '##ce'],
'YC': ['y', '##c'],
'?': ['[UNK]'],
'unknown': ['u', '##nk', '##now', '##n']
}
if word in mapping:
return mapping[word]
else:
return [word.lower()]
mocked_tokenizer = Mock()
mocked_tokenizer.tokenize = tokenize
tokens, text2token, token2text = tokenize_and_map(mocked_tokenizer, sentence)
assert tokens == expected_tokens
assert text2token == expected_text2token
assert token2text == expected_token2text
```
---
## 動DB - 好可怕 - Unit Test
```python=
def test_get_data_for_recommend(mocker):
logger = Mock()
customer_id = 1
method = 'approach_target_saa'
thres_of_weights = 0.01
turn_on_constraints = {'industry': True, 'country': True}
turn_on_constraints_list = \
[name for name, turn_on in turn_on_constraints.items() if turn_on is True]
# patch db query User
mocked_user = [m.User(_product_weights={0: 0.5, 1: 0.5})]
mocker.patch('driver_utils.User.query', MockedQueryWrapper(mocked_user))
# patch db query Product
mocked_product = [m.Product(product_id=0,
product_name='TW000T3223Y2',
history_return=0.8),
m.Product(product_id=1,
product_name='TW000T4301Y5',
history_return=0.9)]
mocker.patch('driver_utils.Product.query', MockedQueryWrapper(mocked_product))
# patch db query Benchmark
mocked_benchmark = [m.Benchmark(market_type='country',
benchmark_id=0,
benchmark_name='SPX Index',
saa_weight=0.7,
saa_weight_lower=0.2,
saa_weight_upper=0.8),
m.Benchmark(market_type='country',
benchmark_id=1,
benchmark_name='SXXP Index',
saa_weight=0.2,
saa_weight_lower=0,
saa_weight_upper=0.5),
m.Benchmark(market_type='country',
benchmark_id=2,
benchmark_name='NKY Index',
saa_weight=0.1,
saa_weight_lower=0,
saa_weight_upper=0.5),
m.Benchmark(market_type='industry',
benchmark_id=3,
benchmark_name='非核心消費',
saa_weight=0.3,
saa_weight_lower=0.2,
saa_weight_upper=0.8),
m.Benchmark(market_type='industry',
benchmark_id=4,
benchmark_name='核心消費',
saa_weight=0.3,
saa_weight_lower=0,
saa_weight_upper=0.5),
m.Benchmark(market_type='industry',
benchmark_id=5,
benchmark_name='能源',
saa_weight=0.4,
saa_weight_lower=0,
saa_weight_upper=0.5)]
mocker.patch('driver_utils.Benchmark.query', MockedQueryWrapper(mocked_benchmark))
# patch db query Projection
mocked_projection = [m.Projection(product_id=0,
_weights={0: 0.3,
1: 0.3,
2: 0.4,
3: 0.3,
4: 0.3,
5: 0.4}),
m.Projection(product_id=1,
_weights={0: 0.2,
1: 0.2,
2: 0.6,
3: 0.2,
4: 0.2,
5: 0.6})]
mocker.patch('driver_utils.Projection.query', MockedQueryWrapper(mocked_projection))
# patch db query Config
mocked_config = [m.Config(key='risk_free_rate', val=0.01)]
mocker.patch('driver_utils.Config.query', MockedQueryWrapper(mocked_config))
# patch db query ProductHistoryCovariance
mocked_product_history_covariance = [m.ProductHistoryCovariance(product_id=0,
_covariance={0: 0.01,
1: 0.5}),
m.ProductHistoryCovariance(product_id=1,
_covariance={0: 0.5,
1: 0.8})]
mocker.patch('driver_utils.ProductHistoryCovariance.query',
MockedQueryWrapper(mocked_product_history_covariance))
# ================= Expected data =================
product_mapping = {x.product_id: x.product_name for x in mocked_product}
# User portfolio
product_codes = list()
portfolio_weights = list()
for product_id, weight in mocked_user[0].product_weights.items():
product_codes.append(product_mapping[product_id])
portfolio_weights.append(weight)
# saa
saa_country_dict = {'country': [x.benchmark_name for x in mocked_benchmark
if x.market_type == 'country'],
'weights': [x.saa_weight for x in mocked_benchmark
if x.market_type == 'country'],
'lower_bound': [x.saa_weight_lower for x in mocked_benchmark
if x.market_type == 'country'],
'upper_bound': [x.saa_weight_upper for x in mocked_benchmark
if x.market_type == 'country']}
saa_country_df = pd.DataFrame(saa_country_dict).set_index('country')
saa_industry_dict = {'industry': [x.benchmark_name for x in mocked_benchmark
if x.market_type == 'industry'],
'weights': [x.saa_weight for x in mocked_benchmark
if x.market_type == 'industry'],
'lower_bound': [x.saa_weight_lower for x in mocked_benchmark
if x.market_type == 'industry'],
'upper_bound': [x.saa_weight_upper for x in mocked_benchmark
if x.market_type == 'industry']}
saa_industry_df = pd.DataFrame(saa_industry_dict).set_index('industry')
saa_df = {'country': saa_country_df,
'industry': saa_industry_df}
# projection matrix
projection_country_dict = dict()
country_index_list = [x.benchmark_name for x in mocked_benchmark
if x.market_type == 'country']
for obj in mocked_projection:
product_name = product_mapping[obj.product_id]
projection_matrix = list()
for benchmark_obj in mocked_benchmark:
if benchmark_obj.market_type == 'country':
projection_matrix.append(obj.weights[benchmark_obj.benchmark_id])
projection_country_dict[product_name] = projection_matrix
projection_country_df = pd.DataFrame(projection_country_dict,
index=country_index_list)
projection_industry_dict = dict()
industry_index_list = [x.benchmark_name for x in mocked_benchmark
if x.market_type == 'industry']
for obj in mocked_projection:
product_name = product_mapping[obj.product_id]
projection_matrix = list()
for benchmark_obj in mocked_benchmark:
if benchmark_obj.market_type == 'industry':
projection_matrix.append(obj.weights[benchmark_obj.benchmark_id])
projection_industry_dict[product_name] = projection_matrix
projection_industry_df = pd.DataFrame(projection_industry_dict,
index=industry_index_list)
projection_matrix_df = {'country': projection_country_df,
'industry': projection_industry_df}
# funds mean return
funds_mean_return = {'codes': product_codes,
'returns': [x.history_return for x in mocked_product]}
# funds variance convariance
funds_varcov_dict = dict()
for obj in mocked_product_history_covariance:
cov_list = [obj.covariance[0], obj.covariance[1]]
funds_varcov_dict[product_mapping[obj.product_id]] = cov_list
funds_varcov_df = pd.DataFrame(funds_varcov_dict,
index=product_codes)
# risk free rate
risk_free_rate = [x.val for x in mocked_config if x.key == 'risk_free_rate'][0]
expected_data = {
'id': customer_id,
'method': method,
'product_codes': product_codes,
'portfolio_weights': portfolio_weights,
'strategic_asset_allocation': saa_df,
'projection_matrix': projection_matrix_df,
'risk_free_rate': risk_free_rate,
'product_mean_return': funds_mean_return,
'product_varcov': funds_varcov_df,
'thres_of_weights': thres_of_weights,
'turn_on_constraints': turn_on_constraints_list
}
# ================= Function that we want to test =================
data = get_data_for_recommend(customer_id,
method,
thres_of_weights,
turn_on_constraints,
logger)
for key, val in expected_data.items():
if isinstance(val, dict):
for sub_key, sub_val in val.items():
if isinstance(sub_val, pd.DataFrame):
assert_frame_equal(data[key][sub_key], sub_val)
else:
assert data[key][sub_key] == sub_val
elif isinstance(val, pd.DataFrame):
assert_frame_equal(data[key], val)
else:
assert data[key] == val
```