99 lines
2.8 KiB
Python
99 lines
2.8 KiB
Python
import gzip
|
|
import json
|
|
|
|
from api.utils.character_response import (
|
|
character_response_cache_key,
|
|
character_response_encoding,
|
|
clear_character_response_local_cache,
|
|
get_character_response_bytes,
|
|
)
|
|
from config.main import config
|
|
|
|
|
|
def setup_function():
|
|
clear_character_response_local_cache()
|
|
|
|
|
|
def teardown_function():
|
|
clear_character_response_local_cache()
|
|
|
|
|
|
def test_character_response_encoding_matches_gzip_middleware():
|
|
assert character_response_encoding('gzip, deflate, br') == 'gzip'
|
|
assert character_response_encoding('identity') == 'identity'
|
|
assert character_response_encoding(None) == 'identity'
|
|
|
|
|
|
def test_character_response_caches_final_gzip_bytes_locally():
|
|
calls = 0
|
|
|
|
def load_info():
|
|
nonlocal calls
|
|
calls += 1
|
|
return {'alter': 'weapon_master', 'skills': []}
|
|
|
|
first = get_character_response_bytes(None, 'GF.swordman_male.weapon_master', '0', 'gzip', load_info)
|
|
second = get_character_response_bytes(None, 'GF.swordman_male.weapon_master', '0', 'gzip', load_info)
|
|
|
|
assert first == second
|
|
assert calls == 1
|
|
assert json.loads(gzip.decompress(first)) == {
|
|
'code': 200,
|
|
'message': 'Success',
|
|
'data': {'alter': 'weapon_master', 'skills': []},
|
|
}
|
|
|
|
|
|
def test_character_response_caches_identity_and_gzip_separately():
|
|
calls = 0
|
|
|
|
def load_info():
|
|
nonlocal calls
|
|
calls += 1
|
|
return {'name': '极诣·剑魂'}
|
|
|
|
identity = get_character_response_bytes(None, 'GF.swordman_male.weapon_master', '0', 'identity', load_info)
|
|
compressed = get_character_response_bytes(None, 'GF.swordman_male.weapon_master', '0', 'gzip', load_info)
|
|
|
|
assert calls == 2
|
|
assert gzip.decompress(compressed) == identity
|
|
assert json.loads(identity)['data']['name'] == '极诣·剑魂'
|
|
|
|
|
|
def test_character_response_reuses_redis_final_bytes_after_local_cache_clear(monkeypatch):
|
|
class FakeRedis:
|
|
def __init__(self):
|
|
self.values = {}
|
|
|
|
def get(self, key):
|
|
return self.values.get(key)
|
|
|
|
def set(self, key, value):
|
|
self.values[key] = value
|
|
|
|
redis = FakeRedis()
|
|
monkeypatch.setattr(config, 'DEBUG_MODE', False)
|
|
first = get_character_response_bytes(
|
|
redis,
|
|
'GF.swordman_male.weapon_master',
|
|
'0',
|
|
'gzip',
|
|
lambda: {'alter': 'weapon_master'},
|
|
)
|
|
clear_character_response_local_cache()
|
|
|
|
def fail_to_load_info():
|
|
raise AssertionError('Redis cache hit must not rebuild character info')
|
|
|
|
second = get_character_response_bytes(
|
|
redis,
|
|
'GF.swordman_male.weapon_master',
|
|
'0',
|
|
'gzip',
|
|
fail_to_load_info,
|
|
)
|
|
|
|
redis_key = character_response_cache_key('GF.swordman_male.weapon_master', '0', 'gzip')
|
|
assert redis.values[redis_key] == first
|
|
assert second == first
|