diff --git a/notecard/notecard.py b/notecard/notecard.py index fabd7d1..88d2ab1 100644 --- a/notecard/notecard.py +++ b/notecard/notecard.py @@ -111,10 +111,11 @@ class Notecard: def __init__(self, debug=False): """Initialize the Notecard object.""" + self.__version__ = self._fetch_version() self._user_agent_app = None self._user_agent_sent = False self._user_agent = { - 'agent': 'note-python', + 'agent': f'note-python {self.__version__}'.strip(), 'os_name': sys.implementation.name, 'os_platform': sys.platform, 'os_version': sys.version @@ -129,6 +130,22 @@ def __init__(self, debug=False): self._card_supports_crc = False self._reset_required = True + def _fetch_version(self): + """Fetch the version of the note-python library.""" + try: + # Check development version + import tomllib + with open('pyproject.toml', 'rb') as f: + data = tomllib.load(f) + return data['project']['version'] + except Exception: + # Check installed version + try: + import importlib.metadata + return importlib.metadata.version('note-python') + except Exception: + return '' + def _crc_add(self, req_string, seq_number): """Add a CRC field to the request. diff --git a/test/test_notecard.py b/test/test_notecard.py index 08c1d06..00c2db8 100644 --- a/test/test_notecard.py +++ b/test/test_notecard.py @@ -442,12 +442,27 @@ def test_get_user_agent(self): card = notecard.Notecard() userAgent = card.GetUserAgent() - assert userAgent['agent'] == 'note-python' + expected_agent = f'note-python {card.__version__}'.strip() + assert userAgent['agent'] == expected_agent assert userAgent['os_name'] is not None assert userAgent['os_platform'] is not None assert userAgent['os_version'] is not None assert userAgent['os_family'] is not None + def test_get_user_agent_with_custom_version(self): + with patch.object(notecard.Notecard, '_fetch_version', return_value='1.1.1'): + card = notecard.Notecard() + userAgent = card.GetUserAgent() + + assert userAgent['agent'] == 'note-python 1.1.1' + + def test_get_user_agent_with_missing_version(self): + with patch.object(notecard.Notecard, '_fetch_version', return_value=''): + card = notecard.Notecard() + userAgent = card.GetUserAgent() + + assert userAgent['agent'] == 'note-python' + # SetAppUserAgent tests. def set_user_agent_info(self, info=None): card = notecard.Notecard()