From 42a8f4278df701943632d6b0e9607202487a9b8e Mon Sep 17 00:00:00 2001 From: Aaron Steers Date: Tue, 12 Mar 2024 14:31:15 -0700 Subject: [PATCH] add unit tests --- .../unit_tests/test_anonymous_usage_stats.py | 48 +++++++++++++++++-- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/tests/unit_tests/test_anonymous_usage_stats.py b/tests/unit_tests/test_anonymous_usage_stats.py index b1b953e8..98de3c60 100644 --- a/tests/unit_tests/test_anonymous_usage_stats.py +++ b/tests/unit_tests/test_anonymous_usage_stats.py @@ -4,8 +4,10 @@ import itertools from contextlib import nullcontext as does_not_raise import json +import os +from pathlib import Path import re -from unittest.mock import Mock, call, patch +from unittest.mock import MagicMock, call, patch from freezegun import freeze_time import responses @@ -16,8 +18,6 @@ from airbyte.version import get_version import airbyte as ab from airbyte._util import telemetry -import requests -import datetime @responses.activate @@ -174,3 +174,45 @@ def test_tracking( } ) ]) + +def test_setup_analytics_existing_file(monkeypatch): + # Mock the environment variable and the analytics file + monkeypatch.setattr(Path, 'exists', lambda x: True) + monkeypatch.setattr(Path, 'read_text', lambda x: "anonymous_user_id: test_id\n") + assert telemetry._setup_analytics() == 'test_id' + + +def test_setup_analytics_missing_file(monkeypatch): + """Mock the environment variable and the missing analytics file.""" + monkeypatch.setenv(telemetry._ENV_ANALYTICS_ID, 'test_id') + monkeypatch.setattr(Path, 'exists', lambda x: False) + + mock_path = MagicMock() + monkeypatch.setattr(Path, 'write_text', mock_path) + + assert telemetry._setup_analytics() == 'test_id' + + assert mock_path.call_count == 1 + + +def test_setup_analytics_corrupt_file(monkeypatch): + """Mock the environment variable and the missing analytics file.""" + monkeypatch.setattr(Path, 'exists', lambda x: True) + monkeypatch.setattr(Path, 'read_text', lambda x: "not-a-valid ::: yaml file\n") + + mock = MagicMock() + monkeypatch.setattr(Path, 'write_text', mock) + + assert telemetry._setup_analytics() + + assert mock.call_count == 1 + + +def test_get_analytics_id(monkeypatch): + # Mock the _ANALYTICS_ID variable + monkeypatch.setattr(telemetry, '_ANALYTICS_ID', 'test_id') + + mock = MagicMock() + monkeypatch.setattr(Path, 'write_text', mock) + + assert telemetry._get_analytics_id() == 'test_id'