Skip to content

Commit bbd4dfd

Browse files
author
Inbal Tako
committed
Add coverage tests
1 parent 1c5405d commit bbd4dfd

14 files changed

Lines changed: 816 additions & 14 deletions

requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
requests~=2.23.0
2+
pycrypto~=2.6.1
3+
crypto==1.4.1

securenative/event_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ def stop_event_persist(self):
133133
try:
134134
if self.thread:
135135
self.thread.stop()
136-
self.scheduler.cancel(self._send_events)
136+
self.scheduler.cancel(self._send_events)
137137
except ValueError as e:
138138
Logger.error("Could not stop event scheduler; {}".format(e))
139139

securenative/securenative.py

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44
from securenative.context.context_builder import ContextBuilder
55
from securenative.event_manager import EventManager
66
from securenative.exceptions.securenative_config_exception import SecureNativeConfigException
7+
from securenative.exceptions.securenative_sdk_Illegal_state_exception import SecureNativeSDKIllegalStateException
78
from securenative.exceptions.securenative_sdk_exception import SecureNativeSDKException
89
from securenative.logger import Logger
910
from securenative.utils.utils import Utils
1011

1112

1213
class SecureNative:
14+
_securenative = None
1315

1416
def __init__(self, options):
1517
if Utils.is_null_or_empty(options.api_key):
@@ -22,36 +24,44 @@ def __init__(self, options):
2224
self._event_manager.start_event_persist()
2325

2426
self._api_manager = ApiManager(self._event_manager, self._options)
25-
self._securenative = None
2627
Logger.init_logger(self._options.log_level)
2728

28-
def init(self, options):
29-
if self._securenative is None:
30-
self._securenative = SecureNative(options)
31-
return self._securenative
29+
def __exit__(self, exc_type, exc_val, exc_tb):
30+
self._event_manager.stop_event_persist()
31+
32+
@classmethod
33+
def init_with_options(cls, options):
34+
if cls._securenative is None:
35+
cls._securenative = SecureNative(options)
36+
return cls._securenative
3237
else:
3338
Logger.debug('This SDK was already initialized.')
3439
raise SecureNativeSDKException(u'This SDK was already initialized.')
3540

36-
def init(self, api_key):
41+
@classmethod
42+
def init_with_api_key(cls, api_key):
3743
if Utils.is_null_or_empty(api_key):
3844
raise SecureNativeConfigException("You must pass your SecureNative api key")
3945

40-
if self._securenative is None:
46+
if cls._securenative is None:
4147
builder = ConfigurationBuilder().default_config_builder()
4248
options = builder.with_api_key(api_key)
43-
self._securenative = SecureNative(options)
44-
return self._securenative
49+
cls._securenative = SecureNative(options)
50+
return cls._securenative
4551
else:
4652
Logger.debug('This SDK was already initialized.')
4753
raise SecureNativeSDKException(u'This SDK was already initialized.')
4854

49-
def init(self):
55+
@classmethod
56+
def init(cls):
5057
options = ConfigurationManager.load_config()
51-
return self.init(options)
58+
return cls.init_with_options(options)
5259

53-
def get_instance(self):
54-
return self._securenative
60+
@classmethod
61+
def get_instance(cls):
62+
if not cls._securenative:
63+
raise SecureNativeSDKIllegalStateException()
64+
return cls._securenative
5565

5666
def get_options(self):
5767
return self._options
@@ -69,3 +79,7 @@ def track(self, event_options):
6979

7080
def verify(self, event_options):
7181
self._api_manager.verify(event_options)
82+
83+
@classmethod
84+
def _flush(cls):
85+
cls._securenative = None

tests/__init__.py

Whitespace-only changes.

tests/api_manager_test.py

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
import unittest
2+
3+
from securenative.api_manager import ApiManager
4+
from securenative.config.configuration_manager import ConfigurationManager
5+
from securenative.context.context_builder import ContextBuilder
6+
from securenative.enums.event_types import EventTypes
7+
from securenative.enums.risk_level import RiskLevel
8+
from securenative.event_manager import EventManager
9+
from securenative.event_options_builder import EventOptionsBuilder
10+
from securenative.exceptions.securenative_invalid_options_exception import SecureNativeInvalidOptionsException
11+
from securenative.models.user_traits import UserTraits
12+
from securenative.models.verify_result import VerifyResult
13+
from securenative.utils.date_utils import DateUtils
14+
15+
16+
class ApiManagerTest(unittest.TestCase):
17+
18+
def setUp(self):
19+
self.context = ContextBuilder(). \
20+
with_ip("127.0.0.1"). \
21+
with_client_token("SECURED_CLIENT_TOKEN"). \
22+
with_headers(
23+
{
24+
"user-agent": "Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405"
25+
}).build()
26+
27+
self.event_options = EventOptionsBuilder(EventTypes.LOG_IN). \
28+
with_user_id("USER_ID"). \
29+
with_user_traits(UserTraits("USER_NAME", "USER_EMAIL")). \
30+
with_context(self.context). \
31+
with_properties({"prop1": "CUSTOM_PARAM_VALUE",
32+
"prop2": True,
33+
"prop3": 3}).with_timestamp(DateUtils.to_timestamp(None)).build()
34+
35+
def test_track_event(self):
36+
options = ConfigurationManager.config_builder(). \
37+
with_api_key("YOUR_API_KEY"). \
38+
with_auto_send(True). \
39+
with_interval(10)
40+
41+
client = MockHttpClient() # TODO!
42+
event_manager = EventManager(options, client)
43+
event_manager.start_event_persist()
44+
api_manager = ApiManager(event_manager, options)
45+
46+
try:
47+
res = api_manager.track(self.event_options)
48+
expected = "{\"eventType\":\"sn.user.login\",\"userId\":\"USER_ID\",\"userTraits\":{" \
49+
"\"name\":\"USER_NAME\",\"email\":\"USER_EMAIL\",\"createdAt\":null},\"request\":{" \
50+
"\"cid\":null,\"vid\":null,\"fp\":null,\"ip\":\"127.0.0.1\",\"remoteIp\":null,\"headers\":{" \
51+
"\"user-agent\":\"Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) " \
52+
"AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405\"},\"url\":null,\"method\":null}," \
53+
"\"properties\":{\"prop2\":true,\"prop1\":\"CUSTOM_PARAM_VALUE\",\"prop3\":3}} "
54+
55+
self.assertEqual(res.body, expected)
56+
finally:
57+
event_manager.stop_event_persist()
58+
59+
def test_securenative_invalid_options_exception(self):
60+
options = ConfigurationManager.config_builder(). \
61+
with_api_key("YOUR_API_KEY"). \
62+
with_auto_send(True). \
63+
with_interval(10)
64+
65+
properties = {}
66+
for i in range(1, 12):
67+
properties[i] = i
68+
69+
client = MockHttpClient() # TODO!
70+
event_manager = EventManager(client, options)
71+
event_manager.start_event_persist()
72+
api_manager = ApiManager(event_manager, options)
73+
74+
try:
75+
api_manager.track(EventOptionsBuilder(
76+
EventTypes.LOG_IN).with_properties(properties).build())
77+
self.assertRaises(SecureNativeInvalidOptionsException)
78+
finally:
79+
event_manager.stop_event_persist()
80+
81+
def test_automatic_persistent_disable(self):
82+
options = ConfigurationManager.config_builder(). \
83+
with_api_key("YOUR_API_KEY"). \
84+
with_auto_send(True). \
85+
with_interval(10)
86+
87+
client = MockHttpClient() # TODO!
88+
event_manager = EventManager(client, options)
89+
api_manager = ApiManager(event_manager, options)
90+
91+
self.assertIsNotNone(api_manager.track(self.event_options))
92+
93+
def test_unauthorized_track_event(self):
94+
options = ConfigurationManager.config_builder(). \
95+
with_api_key("YOUR_API_KEY"). \
96+
with_auto_send(True). \
97+
with_interval(10)
98+
99+
client = MockHttpClient() # TODO!
100+
event_manager = EventManager(client, options)
101+
event_manager.start_event_persist()
102+
api_manager = ApiManager(event_manager, options)
103+
104+
try:
105+
self.assertIsNotNone(api_manager.track(self.event_options))
106+
finally:
107+
event_manager.stop_event_persist()
108+
109+
def test_verify_event(self):
110+
options = ConfigurationManager.config_builder(). \
111+
with_api_key("YOUR_API_KEY")
112+
113+
verify_result = VerifyResult(RiskLevel.LOW, 0, {})
114+
115+
client = MockHttpClient() # TODO!
116+
event_manager = EventManager(client, options)
117+
event_manager.start_event_persist()
118+
api_manager = ApiManager(event_manager, options)
119+
120+
result, body = api_manager.verify(self.event_options)
121+
122+
self.assertEqual(result.risk_level, verify_result.risk_level)
123+
self.assertEqual(result.score, verify_result.score)
124+
self.assertEqual(result.triggers, verify_result.triggers)
125+
126+
expected = "{\"eventType\":\"sn.user.login\",\"userId\":\"USER_ID\",\"userTraits\":{\"name\":\"USER_NAME\",\"email\":\"USER_EMAIL\",\"createdAt\":null},\"request\":{\"cid\":null,\"vid\":null,\"fp\":null,\"ip\":\"127.0.0.1\",\"remoteIp\":null,\"headers\":{\"user-agent\":\"Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405\"},\"url\":null,\"method\":null},\"properties\":{\"prop2\":true,\"prop1\":\"CUSTOM_PARAM_VALUE\",\"prop3\":3}}";
127+
self.assertEqual(body, expected)
128+
129+
def test_unauthorized_verify_event(self):
130+
options = ConfigurationManager.config_builder(). \
131+
with_api_key("YOUR_API_KEY")
132+
133+
client = MockHttpClient() # TODO!
134+
event_manager = EventManager(client, options)
135+
event_manager.start_event_persist()
136+
api_manager = ApiManager(event_manager, options)
137+
138+
result, body = api_manager.verify(self.event_options)
139+
140+
self.assertIsNotNone(result)
141+
self.assertEqual(result.risk_level, RiskLevel.LOW)
142+
self.assertEqual(result.score, 0)
143+
self.assertEqual(result.triggers, 0)
144+
145+
expected = "{\"eventType\":\"sn.user.login\",\"userId\":\"USER_ID\",\"userTraits\":{\"name\":\"USER_NAME'\",\"email\":\"USER_EMAIL'\",\"createdAt\":null},\"request\":{\"cid\":null,\"vid\":null,\"fp\":null,\"ip\":\"127.0.0.1\",\"remoteIp\":null,\"headers\":{\"user-agent\":\"Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405\"},\"url\":null,\"method\":null},\"properties\":{\"prop2\":true,\"prop1\":\"CUSTOM_PARAM_VALUE\",\"prop3\":3}}";
146+
self.assertIsNotNone(body)
147+
self.assertEqual(body, expected)
148+
149+
150+
if __name__ == '__main__':
151+
unittest.main()

0 commit comments

Comments
 (0)