python-opendata-transport 0.5.0__tar.gz → 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. python_opendata_transport-0.6.0/.github/workflows/publish-to-pypi.yml +41 -0
  2. {python_opendata_transport-0.5.0 → python_opendata_transport-0.6.0}/.github/workflows/python.yml +13 -7
  3. {python_opendata_transport-0.5.0 → python_opendata_transport-0.6.0}/CHANGES.txt +7 -0
  4. {python_opendata_transport-0.5.0 → python_opendata_transport-0.6.0}/LICENSE +1 -1
  5. {python_opendata_transport-0.5.0 → python_opendata_transport-0.6.0}/PKG-INFO +15 -12
  6. {python_opendata_transport-0.5.0 → python_opendata_transport-0.6.0}/README.rst +1 -1
  7. {python_opendata_transport-0.5.0 → python_opendata_transport-0.6.0}/example.py +20 -1
  8. {python_opendata_transport-0.5.0 → python_opendata_transport-0.6.0}/opendata_transport/__init__.py +73 -22
  9. python_opendata_transport-0.6.0/pyproject.toml +53 -0
  10. python_opendata_transport-0.6.0/tests/__init__.py +1 -0
  11. python_opendata_transport-0.6.0/tests/test_opendata_transport.py +132 -0
  12. python_opendata_transport-0.5.0/MANIFEST.in +0 -1
  13. python_opendata_transport-0.5.0/python_opendata_transport.egg-info/PKG-INFO +0 -65
  14. python_opendata_transport-0.5.0/python_opendata_transport.egg-info/SOURCES.txt +0 -17
  15. python_opendata_transport-0.5.0/python_opendata_transport.egg-info/dependency_links.txt +0 -1
  16. python_opendata_transport-0.5.0/python_opendata_transport.egg-info/requires.txt +0 -2
  17. python_opendata_transport-0.5.0/python_opendata_transport.egg-info/top_level.txt +0 -1
  18. python_opendata_transport-0.5.0/python_opendata_transport.egg-info/zip-safe +0 -1
  19. python_opendata_transport-0.5.0/setup.cfg +0 -7
  20. python_opendata_transport-0.5.0/setup.py +0 -42
  21. {python_opendata_transport-0.5.0 → python_opendata_transport-0.6.0}/.gitignore +0 -0
  22. {python_opendata_transport-0.5.0 → python_opendata_transport-0.6.0}/opendata_transport/exceptions.py +0 -0
@@ -0,0 +1,41 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ deploy:
12
+
13
+ runs-on: ubuntu-latest
14
+
15
+ environment: release
16
+ permissions:
17
+ id-token: write
18
+
19
+ steps:
20
+ - uses: actions/checkout@v6
21
+
22
+ - name: Set up Python
23
+ uses: actions/setup-python@v6
24
+ with:
25
+ python-version: '3.13'
26
+ cache: 'pip'
27
+
28
+ - name: Install dependencies
29
+ run: |
30
+ python -m pip install --upgrade pip
31
+ pip install hatch
32
+
33
+ - name: Build package
34
+ run: hatch build
35
+
36
+ - name: Run tests with hatch
37
+ run: |
38
+ hatch run test:run
39
+
40
+ - name: Publish package distributions to PyPI
41
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -12,20 +12,26 @@ jobs:
12
12
  runs-on: ubuntu-latest
13
13
  strategy:
14
14
  matrix:
15
- python-version: [ "3.11", "3.12" ]
15
+ python-version: [ "3.13", "3.14" ]
16
16
 
17
17
  steps:
18
- - uses: actions/checkout@v4
18
+ - uses: actions/checkout@v6
19
19
 
20
20
  - name: Set up Python ${{ matrix.python-version }}
21
- uses: actions/setup-python@v5
21
+ uses: actions/setup-python@v6
22
22
  with:
23
23
  python-version: ${{ matrix.python-version }}
24
24
 
25
- - name: Install dependencies
25
+ - name: Install hatch
26
26
  run: |
27
27
  python -m pip install --upgrade pip
28
- python setup.py install
28
+ pip install hatch
29
29
 
30
- - name: Black Code Formatter
31
- uses: jpetrucciani/black-check@22.12.0
30
+ - name: Lint with ruff
31
+ run: |
32
+ pip install ruff
33
+ ruff check .
34
+
35
+ - name: Run tests with hatch
36
+ run: |
37
+ hatch run test:run
@@ -1,6 +1,13 @@
1
1
  Changes
2
2
  =======
3
3
 
4
+ 20260407 - 0.6.0
5
+ ----------------
6
+
7
+ - Update build-system
8
+ - Add unittests
9
+ - Add rate limit stats (thanks @miaucl)
10
+
4
11
  20240929 - 0.5.0
5
12
  ----------------
6
13
 
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2017-2024 Fabian Affolter <fabian@affolter-engineering.ch>
3
+ Copyright (c) 2017-2025 Fabian Affolter <fabian@affolter-engineering.ch>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -1,26 +1,29 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: python_opendata_transport
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: Python API for interacting with transport.opendata.ch.
5
- Home-page: https://github.com/home-assistant-ecosystem/python-opendata-transport
6
- Download-URL: https://github.com/home-assistant-ecosystem/python-opendata-transport/releases
7
- Author: Fabian Affolter
8
- Author-email: fabian@affolter-engineering.ch
5
+ Project-URL: Homepage, https://github.com/home-assistant-ecosystem/python-opendata-transport
6
+ Project-URL: Download URL, https://github.com/home-assistant-ecosystem/python-opendata-transport/releases
7
+ Author-email: Fabian Affolter <fabian@affolter-engineering.ch>
9
8
  License: MIT
10
- Classifier: Development Status :: 3 - Alpha
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
11
  Classifier: Environment :: Console
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: License :: OSI Approved :: MIT License
14
14
  Classifier: Operating System :: MacOS :: MacOS X
15
15
  Classifier: Operating System :: Microsoft :: Windows
16
16
  Classifier: Operating System :: POSIX
17
- Classifier: Programming Language :: Python :: 3.11
18
- Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
19
  Classifier: Topic :: Utilities
20
- Requires-Python: >=3.11
21
- License-File: LICENSE
20
+ Requires-Python: >=3.13
22
21
  Requires-Dist: aiohttp<4,>=3.8.5
23
22
  Requires-Dist: urllib3
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'test'
25
+ Requires-Dist: pytest>=9; extra == 'test'
26
+ Description-Content-Type: text/x-rst
24
27
 
25
28
  python-opendata-transport
26
29
  =========================
@@ -47,7 +50,7 @@ On a Fedora-based system or on a CentOS/RHEL 8 machine with has EPEL enabled.
47
50
 
48
51
  $ sudo dnf -y install python3-opendata-transport
49
52
 
50
- For Nix or NixOS users is a package available. Keep in mind that the lastest releases might only
53
+ For Nix or NixOS users is a package available. Keep in mind that the latest releases might only
51
54
  be present in the ``unstable`` channel.
52
55
 
53
56
  .. code:: bash
@@ -23,7 +23,7 @@ On a Fedora-based system or on a CentOS/RHEL 8 machine with has EPEL enabled.
23
23
 
24
24
  $ sudo dnf -y install python3-opendata-transport
25
25
 
26
- For Nix or NixOS users is a package available. Keep in mind that the lastest releases might only
26
+ For Nix or NixOS users is a package available. Keep in mind that the latest releases might only
27
27
  be present in the ``unstable`` channel.
28
28
 
29
29
  .. code:: bash
@@ -1,4 +1,5 @@
1
1
  """Example to get the details for a connection or a station."""
2
+
2
3
  import asyncio
3
4
 
4
5
  import aiohttp
@@ -16,6 +17,7 @@ async def main():
16
17
  await locations.async_get_data()
17
18
 
18
19
  # Print the locations data
20
+ print("Locations for query 'Stettb':")
19
21
  print(locations.locations)
20
22
 
21
23
  # Print as list
@@ -26,6 +28,8 @@ async def main():
26
28
  await locations.async_get_data()
27
29
 
28
30
  # Print the locations data
31
+ print()
32
+ print("Locations for coordinates (47.2, 8.7):")
29
33
  print(locations.locations)
30
34
 
31
35
  # Print as list
@@ -35,19 +39,33 @@ async def main():
35
39
 
36
40
  # Get the connection for a defined route
37
41
  connection = OpendataTransport(
38
- "Zürich, Blumenfeldstrasse", "Zürich Oerlikon, Bahnhof", session, 4
42
+ "Zürich, Blumenfeldstrasse",
43
+ "Zürich Oerlikon, Bahnhof",
44
+ session,
45
+ 4,
46
+ enable_rate_limit_stats=True,
39
47
  )
40
48
  await connection.async_get_data()
41
49
 
42
50
  # Print the start and the destination name
51
+ print()
43
52
  print("Train connections:", connection.from_name, "->", connection.to_name)
44
53
 
45
54
  # Print the next three connections
55
+ print()
56
+ print("Next three connections:")
46
57
  print(connection.connections)
47
58
 
48
59
  # Print the details of the next connection
60
+ print()
61
+ print("Details of the next connection:")
49
62
  print(connection.connections[0])
50
63
 
64
+ # Print the rate limit stats
65
+ print()
66
+ print("Rate limit stats:")
67
+ print(connection.rate_limit_stats)
68
+
51
69
  print()
52
70
 
53
71
  # Get all connections of a station
@@ -55,6 +73,7 @@ async def main():
55
73
  await stationboard.async_get_data()
56
74
 
57
75
  # Print the journey data
76
+ print("Stationboard")
58
77
  print(stationboard.journeys)
59
78
 
60
79
 
@@ -1,6 +1,8 @@
1
1
  """Wrapper to get connection details from Opendata Transport."""
2
+
2
3
  import asyncio
3
4
  import logging
5
+ from datetime import datetime, timedelta
4
6
 
5
7
  import aiohttp
6
8
  import urllib.parse
@@ -8,14 +10,30 @@ import urllib.parse
8
10
  from . import exceptions
9
11
 
10
12
  _LOGGER = logging.getLogger(__name__)
13
+ if not logging.getLogger().hasHandlers():
14
+ logging.basicConfig(level=logging.INFO)
11
15
  _RESOURCE_URL = "http://transport.opendata.ch/v1/"
16
+ _DEFAULT_RATE_LIMIT_STATS_HISTORY = 7 # default 7 days
12
17
 
13
18
 
14
19
  class OpendataTransportBase(object):
15
20
  """Representation of the Opendata Transport base class"""
16
21
 
17
- def __init__(self, session):
22
+ def __init__(
23
+ self,
24
+ session,
25
+ enable_rate_limit_stats=False,
26
+ rate_limit_stats_history=_DEFAULT_RATE_LIMIT_STATS_HISTORY,
27
+ ):
18
28
  self._session = session
29
+ self._enable_rate_limit_stats = enable_rate_limit_stats
30
+ self._rate_limit_stats_history = rate_limit_stats_history
31
+ self._rate_limit_stats = {}
32
+
33
+ @property
34
+ def rate_limit_stats(self):
35
+ """Return the rate limit stats."""
36
+ return self._rate_limit_stats.copy()
19
37
 
20
38
  @staticmethod
21
39
  def get_url(resource, params):
@@ -24,16 +42,52 @@ class OpendataTransportBase(object):
24
42
  url = "{resource_url}{resource}?{param}".format(
25
43
  resource_url=_RESOURCE_URL, resource=resource, param=param
26
44
  )
27
- print(url)
28
45
  return url
29
46
 
47
+ def update_stats(self, success: bool = True) -> None:
48
+ """Update the stats and record every call."""
49
+ today = datetime.now().date()
50
+ today_key = today.isoformat()
51
+ keep_dates = [
52
+ (today - timedelta(days=i)).isoformat()
53
+ for i in range(self._rate_limit_stats_history)
54
+ ]
55
+ if today_key not in self._rate_limit_stats:
56
+ self._rate_limit_stats[today_key] = {
57
+ "count": 0,
58
+ "errors": 0,
59
+ "timestamps_success": [],
60
+ "timestamps_error": [],
61
+ }
62
+ for key in [key for key in self._rate_limit_stats if key not in keep_dates]:
63
+ del self._rate_limit_stats[key]
64
+
65
+ _LOGGER.debug(self._rate_limit_stats)
66
+ time_value = datetime.now().time().isoformat()
67
+ self._rate_limit_stats[today_key]["count"] += 1
68
+ if success:
69
+ self._rate_limit_stats[today_key]["timestamps_success"].append(time_value)
70
+ else:
71
+ self._rate_limit_stats[today_key]["errors"] += 1
72
+ self._rate_limit_stats[today_key]["timestamps_error"].append(time_value)
73
+
30
74
 
31
75
  class OpendataTransportLocation(OpendataTransportBase):
32
76
  """A class for handling locations from Opendata Transport."""
33
77
 
34
- def __init__(self, session, query=None, x=None, y=None, type_="all", fields=None):
78
+ def __init__(
79
+ self,
80
+ session,
81
+ query=None,
82
+ x=None,
83
+ y=None,
84
+ type_="all",
85
+ fields=None,
86
+ enable_rate_limit_stats=False,
87
+ rate_limit_stats_history=_DEFAULT_RATE_LIMIT_STATS_HISTORY,
88
+ ):
35
89
  """Initialize the location."""
36
- super().__init__(session)
90
+ super().__init__(session, enable_rate_limit_stats, rate_limit_stats_history)
37
91
 
38
92
  self.query = query
39
93
  self.x = x
@@ -78,11 +132,14 @@ class OpendataTransportLocation(OpendataTransportBase):
78
132
 
79
133
  _LOGGER.debug("Response from transport.opendata.ch: %s", response.status)
80
134
  data = await response.json()
135
+ self.update_stats(success=True)
81
136
  _LOGGER.debug(data)
82
137
  except asyncio.TimeoutError as e:
138
+ self.update_stats(success=False)
83
139
  _LOGGER.error("Can not load data from transport.opendata.ch")
84
140
  raise exceptions.OpendataTransportConnectionError() from e
85
141
  except aiohttp.ClientError as aiohttpClientError:
142
+ self.update_stats(success=False)
86
143
  _LOGGER.error("Response from transport.opendata.ch: %s", aiohttpClientError)
87
144
  raise exceptions.OpendataTransportConnectionError() from aiohttpClientError
88
145
 
@@ -105,9 +162,11 @@ class OpendataTransportStationboard(OpendataTransportBase):
105
162
  datetime=None,
106
163
  type_="departure",
107
164
  fields=None,
165
+ enable_rate_limit_stats=False,
166
+ rate_limit_stats_history=_DEFAULT_RATE_LIMIT_STATS_HISTORY,
108
167
  ):
109
168
  """Initialize the journey."""
110
- super().__init__(session)
169
+ super().__init__(session, enable_rate_limit_stats, rate_limit_stats_history)
111
170
 
112
171
  self.station = station
113
172
  self.limit = limit
@@ -163,11 +222,14 @@ class OpendataTransportStationboard(OpendataTransportBase):
163
222
 
164
223
  _LOGGER.debug("Response from transport.opendata.ch: %s", response.status)
165
224
  data = await response.json()
225
+ self.update_stats(success=True)
166
226
  _LOGGER.debug(data)
167
227
  except asyncio.TimeoutError as e:
228
+ self.update_stats(success=False)
168
229
  _LOGGER.error("Can not load data from transport.opendata.ch")
169
230
  raise exceptions.OpendataTransportConnectionError() from e
170
231
  except aiohttp.ClientError as aiohttpClientError:
232
+ self.update_stats(success=False)
171
233
  _LOGGER.error("Response from transport.opendata.ch: %s", aiohttpClientError)
172
234
  raise exceptions.OpendataTransportConnectionError() from aiohttpClientError
173
235
 
@@ -202,16 +264,13 @@ class OpendataTransport(OpendataTransportBase):
202
264
  time=None,
203
265
  isArrivalTime=False,
204
266
  transportations=None,
205
- direct=False,
206
- sleeper=False,
207
- couchette=False,
208
- bike=False,
209
- accessibility=None,
210
267
  via=None,
211
268
  fields=None,
269
+ enable_rate_limit_stats=False,
270
+ rate_limit_stats_history=_DEFAULT_RATE_LIMIT_STATS_HISTORY,
212
271
  ):
213
272
  """Initialize the connection."""
214
- super().__init__(session)
273
+ super().__init__(session, enable_rate_limit_stats, rate_limit_stats_history)
215
274
 
216
275
  self.limit = limit
217
276
  self.page = page
@@ -226,11 +285,6 @@ class OpendataTransport(OpendataTransportBase):
226
285
  if transportations is not None and isinstance(transportations, list)
227
286
  else None
228
287
  )
229
- self.direct = 1 if direct else 0
230
- self.sleeper = 1 if sleeper else 0
231
- self.couchette = 1 if couchette else 0
232
- self.bike = 1 if bike else 0
233
- self.accessibility = accessibility
234
288
  self.fields = (
235
289
  fields if fields is not None and isinstance(fields, list) else None
236
290
  )
@@ -271,10 +325,6 @@ class OpendataTransport(OpendataTransportBase):
271
325
  "limit": self.limit,
272
326
  "page": self.page,
273
327
  "isArrivalTime": self.isArrivalTime,
274
- "direct": self.direct,
275
- "sleeper": self.sleeper,
276
- "couchette": self.couchette,
277
- "bike": self.bike,
278
328
  }
279
329
  if self.via:
280
330
  params["via"] = self.via
@@ -284,8 +334,6 @@ class OpendataTransport(OpendataTransportBase):
284
334
  params["date"] = self.date
285
335
  if self.transportations:
286
336
  params["transportations"] = self.transportations
287
- if self.accessibility:
288
- params["accessibility"] = self.accessibility
289
337
  if self.fields:
290
338
  params["fields"] = self.fields
291
339
 
@@ -296,11 +344,14 @@ class OpendataTransport(OpendataTransportBase):
296
344
 
297
345
  _LOGGER.debug("Response from transport.opendata.ch: %s", response.status)
298
346
  data = await response.json()
347
+ self.update_stats(success=True)
299
348
  _LOGGER.debug(data)
300
349
  except asyncio.TimeoutError as e:
350
+ self.update_stats(success=False)
301
351
  _LOGGER.error("Can not load data from transport.opendata.ch")
302
352
  raise exceptions.OpendataTransportConnectionError() from e
303
353
  except aiohttp.ClientError as aiohttpClientError:
354
+ self.update_stats(success=False)
304
355
  _LOGGER.error("Response from transport.opendata.ch: %s", aiohttpClientError)
305
356
  raise exceptions.OpendataTransportConnectionError() from aiohttpClientError
306
357
 
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "python_opendata_transport"
7
+ version = "0.6.0"
8
+ description = "Python API for interacting with transport.opendata.ch."
9
+ readme = "README.rst"
10
+ license = { text = "MIT" }
11
+ authors = [
12
+ { name = "Fabian Affolter", email = "fabian@affolter-engineering.ch" },
13
+ ]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: MacOS :: MacOS X",
20
+ "Operating System :: Microsoft :: Windows",
21
+ "Operating System :: POSIX",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
+ "Topic :: Utilities",
25
+ ]
26
+ requires-python = ">=3.13"
27
+
28
+ dependencies = [
29
+ "aiohttp>=3.8.5,<4",
30
+ "urllib3",
31
+ ]
32
+
33
+ [project.optional-dependencies]
34
+ test = [
35
+ "pytest>=9",
36
+ "pytest-asyncio>=0.21",
37
+ ]
38
+
39
+ [tool.hatch.envs.test]
40
+ dependencies = [
41
+ "pytest>=9",
42
+ "pytest-asyncio>=0.21",
43
+ "aiohttp>=3.8.4,<4"
44
+ ]
45
+ [tool.hatch.envs.test.scripts]
46
+ run = "pytest"
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ packages = ["opendata_transport"]
50
+
51
+ [project.urls]
52
+ Homepage = "https://github.com/home-assistant-ecosystem/python-opendata-transport"
53
+ "Download URL" = "https://github.com/home-assistant-ecosystem/python-opendata-transport/releases"
@@ -0,0 +1 @@
1
+ """Tests for python-opendata-transport."""
@@ -0,0 +1,132 @@
1
+ """Tests for python-opendata-transport."""
2
+
3
+ import pytest
4
+
5
+ from opendata_transport import (
6
+ OpendataTransportLocation,
7
+ OpendataTransportStationboard,
8
+ OpendataTransport,
9
+ )
10
+ from opendata_transport import exceptions
11
+
12
+
13
+ class DummyResponse:
14
+ """A dummy response to simulate aiohttp.ClientResponse."""
15
+
16
+ def __init__(self, status, json_data):
17
+ """Initialize with a status code and JSON data."""
18
+ self.status = status
19
+ self._json_data = json_data
20
+
21
+ async def json(self):
22
+ """Simulate the json() method of aiohttp.ClientResponse."""
23
+ return self._json_data
24
+
25
+
26
+ class DummySession:
27
+ """A dummy session to simulate aiohttp.ClientSession."""
28
+
29
+ def __init__(self, response):
30
+ """Initialize with a predefined response."""
31
+ self._response = response
32
+
33
+ async def get(self, url, raise_for_status=True):
34
+ """Simulate an HTTP GET request."""
35
+ return self._response
36
+
37
+
38
+ @pytest.mark.asyncio
39
+ async def test_location_success():
40
+ """Test successful retrieval of location data."""
41
+ dummy_json = {
42
+ "stations": [
43
+ {
44
+ "name": "Bern",
45
+ "score": 10,
46
+ "coordinate": {"type": "WGS84", "x": 7.439, "y": 46.948},
47
+ "distance": 0,
48
+ }
49
+ ]
50
+ }
51
+ session = DummySession(DummyResponse(200, dummy_json))
52
+ location = OpendataTransportLocation(session, query="Bern")
53
+ await location.async_get_data()
54
+ assert location.locations[0]["name"] == "Bern"
55
+
56
+
57
+ @pytest.mark.asyncio
58
+ async def test_location_keyerror():
59
+ """Test handling of missing keys in location data."""
60
+ session = DummySession(DummyResponse(200, {}))
61
+ location = OpendataTransportLocation(session, query="Bern")
62
+ with pytest.raises(exceptions.OpendataTransportError):
63
+ await location.async_get_data()
64
+
65
+
66
+ @pytest.mark.asyncio
67
+ async def test_stationboard_success():
68
+ """Test successful retrieval of stationboard data."""
69
+ dummy_json = {
70
+ "stationboard": [
71
+ {
72
+ "stop": {
73
+ "departure": "2024-01-01T12:00:00+01:00",
74
+ "delay": 0,
75
+ "platform": "1",
76
+ },
77
+ "name": "IC 1",
78
+ "category": "IC",
79
+ "number": "1",
80
+ "to": "Geneva",
81
+ }
82
+ ]
83
+ }
84
+ session = DummySession(DummyResponse(200, dummy_json))
85
+ stationboard = OpendataTransportStationboard("Bern", session)
86
+ await stationboard.async_get_data()
87
+ assert stationboard.journeys[0]["name"] == "IC 1"
88
+
89
+
90
+ @pytest.mark.asyncio
91
+ async def test_stationboard_keyerror():
92
+ """Test handling of missing keys in stationboard data."""
93
+ session = DummySession(DummyResponse(200, {}))
94
+ stationboard = OpendataTransportStationboard("Bern", session)
95
+ with pytest.raises(exceptions.OpendataTransportError):
96
+ await stationboard.async_get_data()
97
+
98
+
99
+ @pytest.mark.asyncio
100
+ async def test_connection_success():
101
+ """Test successful retrieval of connection data."""
102
+ dummy_json = {
103
+ "from": {"id": "8507000", "name": "Bern"},
104
+ "to": {"id": "8503000", "name": "Geneva"},
105
+ "connections": [
106
+ {
107
+ "from": {
108
+ "departure": "2024-01-01T12:00:00+01:00",
109
+ "delay": 0,
110
+ "platform": "1",
111
+ },
112
+ "duration": "01:00:00",
113
+ "transfers": 0,
114
+ "sections": [
115
+ {"journey": {"name": "IC 1", "category": "IC", "number": "1"}}
116
+ ],
117
+ }
118
+ ],
119
+ }
120
+ session = DummySession(DummyResponse(200, dummy_json))
121
+ connection = OpendataTransport("Bern", "Geneva", session)
122
+ await connection.async_get_data()
123
+ assert connection.connections[0]["departure"] == "2024-01-01T12:00:00+01:00"
124
+
125
+
126
+ @pytest.mark.asyncio
127
+ async def test_connection_keyerror():
128
+ """Test handling of missing keys in connection data."""
129
+ session = DummySession(DummyResponse(200, {}))
130
+ connection = OpendataTransport("Bern", "Geneva", session)
131
+ with pytest.raises(exceptions.OpendataTransportError):
132
+ await connection.async_get_data()
@@ -1 +0,0 @@
1
- include LICENSE
@@ -1,65 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: python_opendata_transport
3
- Version: 0.5.0
4
- Summary: Python API for interacting with transport.opendata.ch.
5
- Home-page: https://github.com/home-assistant-ecosystem/python-opendata-transport
6
- Download-URL: https://github.com/home-assistant-ecosystem/python-opendata-transport/releases
7
- Author: Fabian Affolter
8
- Author-email: fabian@affolter-engineering.ch
9
- License: MIT
10
- Classifier: Development Status :: 3 - Alpha
11
- Classifier: Environment :: Console
12
- Classifier: Intended Audience :: Developers
13
- Classifier: License :: OSI Approved :: MIT License
14
- Classifier: Operating System :: MacOS :: MacOS X
15
- Classifier: Operating System :: Microsoft :: Windows
16
- Classifier: Operating System :: POSIX
17
- Classifier: Programming Language :: Python :: 3.11
18
- Classifier: Programming Language :: Python :: 3.12
19
- Classifier: Topic :: Utilities
20
- Requires-Python: >=3.11
21
- License-File: LICENSE
22
- Requires-Dist: aiohttp<4,>=3.8.5
23
- Requires-Dist: urllib3
24
-
25
- python-opendata-transport
26
- =========================
27
-
28
- A Python client for interacting with `transport.opendata.ch <http://transport.opendata.ch/>`_.
29
-
30
- This module is the base for the integration into `Home Assistant <https://home-assistant.io>`_
31
- and is simply retrieving the details about a given connection between two stations.
32
-
33
- This module is not official, developed, supported or endorsed by opendata.ch.
34
-
35
- Installation
36
- ------------
37
-
38
- The module is available from the `Python Package Index <https://pypi.python.org/pypi>`_.
39
-
40
- .. code:: bash
41
-
42
- $ pip3 install python_opendata_transport
43
-
44
- On a Fedora-based system or on a CentOS/RHEL 8 machine with has EPEL enabled.
45
-
46
- .. code:: bash
47
-
48
- $ sudo dnf -y install python3-opendata-transport
49
-
50
- For Nix or NixOS users is a package available. Keep in mind that the lastest releases might only
51
- be present in the ``unstable`` channel.
52
-
53
- .. code:: bash
54
-
55
- $ nix-env -iA nixos.python3Packages.python-opendata-transport
56
-
57
- Usage
58
- -----
59
-
60
- The file ``example.py`` contains an example about how to use this module.
61
-
62
- License
63
- -------
64
-
65
- ``python-opendata-transport`` is licensed under MIT, for more details check LICENSE.
@@ -1,17 +0,0 @@
1
- .gitignore
2
- CHANGES.txt
3
- LICENSE
4
- MANIFEST.in
5
- README.rst
6
- example.py
7
- setup.cfg
8
- setup.py
9
- .github/workflows/python.yml
10
- opendata_transport/__init__.py
11
- opendata_transport/exceptions.py
12
- python_opendata_transport.egg-info/PKG-INFO
13
- python_opendata_transport.egg-info/SOURCES.txt
14
- python_opendata_transport.egg-info/dependency_links.txt
15
- python_opendata_transport.egg-info/requires.txt
16
- python_opendata_transport.egg-info/top_level.txt
17
- python_opendata_transport.egg-info/zip-safe
@@ -1,2 +0,0 @@
1
- aiohttp<4,>=3.8.5
2
- urllib3
@@ -1,7 +0,0 @@
1
- [metadata]
2
- description-file = README.rst
3
-
4
- [egg_info]
5
- tag_build =
6
- tag_date = 0
7
-
@@ -1,42 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Setup for the Transport OpenData wrapper."""
3
- import os
4
-
5
- from setuptools import setup, find_packages
6
-
7
-
8
- here = os.path.abspath(os.path.dirname(__file__))
9
-
10
- with open(os.path.join(here, "README.rst"), encoding="utf-8") as readme:
11
- long_description = readme.read()
12
-
13
- setup(
14
- name="python_opendata_transport",
15
- version="0.5.0",
16
- description="Python API for interacting with transport.opendata.ch.",
17
- long_description=long_description,
18
- url="https://github.com/home-assistant-ecosystem/python-opendata-transport",
19
- download_url="https://github.com/home-assistant-ecosystem/python-opendata-transport/releases",
20
- author="Fabian Affolter",
21
- author_email="fabian@affolter-engineering.ch",
22
- license="MIT",
23
- install_requires=[
24
- "aiohttp>=3.8.5,<4",
25
- "urllib3",
26
- ],
27
- packages=find_packages(),
28
- python_requires=">=3.11",
29
- zip_safe=True,
30
- classifiers=[
31
- "Development Status :: 3 - Alpha",
32
- "Environment :: Console",
33
- "Intended Audience :: Developers",
34
- "License :: OSI Approved :: MIT License",
35
- "Operating System :: MacOS :: MacOS X",
36
- "Operating System :: Microsoft :: Windows",
37
- "Operating System :: POSIX",
38
- "Programming Language :: Python :: 3.11",
39
- "Programming Language :: Python :: 3.12",
40
- "Topic :: Utilities",
41
- ],
42
- )