Skip to content

Commit

Permalink
further cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
aviaviavi committed Dec 29, 2024
1 parent f40d5aa commit cf54612
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 41 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ jobs:
- name: Install dependencies
run: |
uv pip install -r requirements-dev.txt
uv pip install ruff pytest
uv pip install -e ".[dev]"
- name: Lint with ruff
run: |
Expand Down
20 changes: 17 additions & 3 deletions examples/send_test_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,45 @@
python examples/send_test_event.py
"""

import os
from requests.exceptions import RequestException

from scarf import ScarfEventLogger


def main():
try:
# Check for required environment variable
if not os.environ.get('SCARF_API_KEY'):
print("Error: SCARF_API_KEY environment variable is not set")
return 1

# Initialize the logger using environment variables
logger = ScarfEventLogger()

# Send a test event with two fields
response = logger.log_event({
success = logger.log_event({
"test_field_1": "hello from scarf-py",
"test_field_2": 42
})

print(f"Response from Scarf: {response}")
if not success:
print("Analytics are disabled via environment variables")
return 0

print("Successfully sent event to Scarf")
return 0

except ValueError as e:
print(f"Configuration error: {e}")
return 1
except RequestException as e:
print(f"Error sending event to Scarf: {e}")
return 1
except Exception as e:
print(f"Unexpected error: {e}")
return 1


if __name__ == "__main__":
main()
exit(main())
3 changes: 0 additions & 3 deletions requirements-dev.txt

This file was deleted.

8 changes: 4 additions & 4 deletions scarf/event_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def log_event(
self,
properties: Dict[str, Any],
timeout: Optional[float] = None,
) -> Optional[bool]:
) -> bool:
"""Log a telemetry event to Scarf.
Args:
Expand All @@ -92,20 +92,20 @@ def log_event(
Overrides the default timeout set in the constructor.
Returns:
True if the event was sent successfully, None if analytics are disabled
True if the event was sent successfully, False if analytics are disabled
Raises:
ValueError: If any property value is not a simple type
requests.exceptions.RequestException: If the request fails or times out
"""
if self._check_do_not_track():
return None
return False

if properties:
self._validate_properties(properties)

response = self.session.post(
f'{self.base_url}',
self.base_url,
params=properties,
timeout=timeout if timeout is not None else self.timeout
)
Expand Down
58 changes: 29 additions & 29 deletions tests/test_event_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def test_validate_properties_complex_types(self):
def test_empty_properties_allowed(self, mock_session):
"""Test that empty properties dictionary is allowed."""
mock_response = MagicMock()
mock_response.json.return_value = {"status": "success"}
mock_response.status_code = 200
mock_session.return_value.post.return_value = mock_response

logger = ScarfEventLogger(api_key="test-api-key")
Expand Down Expand Up @@ -115,7 +115,7 @@ def test_request_timeout(self, mock_session):
def test_request_timeout_override(self, mock_session):
"""Test that per-request timeout overrides the default."""
mock_response = MagicMock()
mock_response.json.return_value = {"status": "success"}
mock_response.status_code = 200
mock_session.return_value.post.return_value = mock_response

logger = ScarfEventLogger(api_key="test-api-key", timeout=3.0)
Expand Down Expand Up @@ -169,35 +169,35 @@ def test_do_not_track_env_var(self, mock_session):
"""Test that DO_NOT_TRACK environment variable disables analytics."""
# Setup mock response
mock_response = MagicMock()
mock_response.json.return_value = {"status": "success"}
mock_response.status_code = 200
mock_session.return_value.post.return_value = mock_response

test_cases = [
('1', True),
('true', True),
('TRUE', True),
('0', False),
('false', False),
('', False),
('1', False),
('true', False),
('TRUE', False),
('0', True),
('false', True),
('', True),
]

test_properties = {'event': 'test', 'value': 42}

for value, expected in test_cases:
for value, should_send in test_cases:
os.environ['DO_NOT_TRACK'] = value
logger = ScarfEventLogger(api_key="test-api-key")
result = logger.log_event(test_properties)

if expected:
self.assertIsNone(result)
mock_session.return_value.post.assert_not_called()
else:
if should_send:
self.assertTrue(result)
mock_session.return_value.post.assert_called_with(
'https://scarf.sh/api/v1',
params=test_properties,
timeout=3.0
)
else:
self.assertFalse(result)
mock_session.return_value.post.assert_not_called()

# Reset mock for next iteration
mock_session.return_value.post.reset_mock()
Expand All @@ -207,35 +207,35 @@ def test_scarf_no_analytics_env_var(self, mock_session):
"""Test that SCARF_NO_ANALYTICS environment variable disables analytics."""
# Setup mock response
mock_response = MagicMock()
mock_response.json.return_value = {"status": "success"}
mock_response.status_code = 200
mock_session.return_value.post.return_value = mock_response

test_cases = [
('1', True),
('true', True),
('TRUE', True),
('0', False),
('false', False),
('', False),
('1', False),
('true', False),
('TRUE', False),
('0', True),
('false', True),
('', True),
]

test_properties = {'event': 'test', 'value': 42}

for value, expected in test_cases:
for value, should_send in test_cases:
os.environ['SCARF_NO_ANALYTICS'] = value
logger = ScarfEventLogger(api_key="test-api-key")
result = logger.log_event(test_properties)

if expected:
self.assertIsNone(result)
mock_session.return_value.post.assert_not_called()
else:
if should_send:
self.assertTrue(result)
mock_session.return_value.post.assert_called_with(
'https://scarf.sh/api/v1',
params=test_properties,
timeout=3.0
)
else:
self.assertFalse(result)
mock_session.return_value.post.assert_not_called()

# Reset mock for next iteration
mock_session.return_value.post.reset_mock()
Expand All @@ -245,15 +245,15 @@ def test_env_var_precedence(self, mock_session):
"""Test that either environment variable can disable analytics."""
# Setup mock response
mock_response = MagicMock()
mock_response.json.return_value = {"status": "success"}
mock_response.status_code = 200
mock_session.return_value.post.return_value = mock_response

os.environ['DO_NOT_TRACK'] = 'false'
os.environ['SCARF_NO_ANALYTICS'] = 'true'
logger = ScarfEventLogger(api_key="test-api-key")

result = logger.log_event({'event': 'test'})
self.assertIsNone(result)
self.assertFalse(result)
mock_session.return_value.post.assert_not_called()

@patch('requests.Session')
Expand All @@ -263,7 +263,7 @@ def mock_post(*args, **kwargs):
if kwargs.get('timeout', float('inf')) < 2:
raise ReadTimeout("Request timed out")
mock_response = MagicMock()
mock_response.json.return_value = {"status": "success"}
mock_response.status_code = 200
return mock_response

mock_session.return_value.post.side_effect = mock_post
Expand Down

0 comments on commit cf54612

Please sign in to comment.