|
11 | 11 |
|
12 | 12 | import pytest
|
13 | 13 | from pygmt.clib.loading import check_libgmt, clib_full_names, clib_names, load_libgmt
|
| 14 | +from pygmt.clib.session import Session |
14 | 15 | from pygmt.exceptions import GMTCLibError, GMTCLibNotFoundError, GMTOSError
|
15 | 16 |
|
16 | 17 |
|
@@ -207,6 +208,44 @@ def test_brokenlib_brokenlib_workinglib(self):
|
207 | 208 | assert check_libgmt(load_libgmt(lib_fullnames=lib_fullnames)) is None
|
208 | 209 |
|
209 | 210 |
|
| 211 | +class TestLibgmtCount: |
| 212 | + """ |
| 213 | + Test that the GMT library is not repeatedly loaded in every session. |
| 214 | + """ |
| 215 | + |
| 216 | + loaded_libgmt = load_libgmt() # Load the GMT library and reuse it when necessary |
| 217 | + counter = 0 # Global counter for how many times ctypes.CDLL is called |
| 218 | + |
| 219 | + def _mock_ctypes_cdll_return(self, libname): # noqa: ARG002 |
| 220 | + """ |
| 221 | + Mock ctypes.CDLL to count how many times the function is called. |
| 222 | +
|
| 223 | + If ctypes.CDLL is called, the counter increases by one. |
| 224 | + """ |
| 225 | + self.counter += 1 # Increase the counter |
| 226 | + return self.loaded_libgmt |
| 227 | + |
| 228 | + def test_libgmt_load_counter(self, monkeypatch): |
| 229 | + """ |
| 230 | + Make sure that the GMT library is not loaded in every session. |
| 231 | + """ |
| 232 | + # Monkeypatch the ctypes.CDLL function |
| 233 | + monkeypatch.setattr(ctypes, "CDLL", self._mock_ctypes_cdll_return) |
| 234 | + |
| 235 | + # Create two sessions and check the global counter |
| 236 | + with Session() as lib: |
| 237 | + _ = lib |
| 238 | + with Session() as lib: |
| 239 | + _ = lib |
| 240 | + assert self.counter == 0 # ctypes.CDLL is not called after two sessions. |
| 241 | + |
| 242 | + # Explicitly calling load_libgmt to make sure the mock function is correct |
| 243 | + load_libgmt() |
| 244 | + assert self.counter == 1 |
| 245 | + load_libgmt() |
| 246 | + assert self.counter == 2 |
| 247 | + |
| 248 | + |
210 | 249 | ###############################################################################
|
211 | 250 | # Test clib_full_names
|
212 | 251 | @pytest.fixture(scope="module", name="gmt_lib_names")
|
|
0 commit comments