Skip to content

Commit f589ff8

Browse files
committed
Add a unittest
1 parent 6936f59 commit f589ff8

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

pygmt/tests/test_clib_loading.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import pytest
1313
from pygmt.clib.loading import check_libgmt, clib_full_names, clib_names, load_libgmt
14+
from pygmt.clib.session import Session
1415
from pygmt.exceptions import GMTCLibError, GMTCLibNotFoundError, GMTOSError
1516

1617

@@ -208,6 +209,45 @@ def test_brokenlib_brokenlib_workinglib(self):
208209
assert check_libgmt(load_libgmt(lib_fullnames=lib_fullnames)) is None
209210

210211

212+
class TestLibgmtCount:
213+
"""
214+
Test that the GMT library is not repeatly loaded in every session.
215+
"""
216+
217+
loaded_libgmt = load_libgmt() # Load the GMT library and reuse it when necessary
218+
counter = 0 # Count how many times ctypes.CDLL is called
219+
220+
def _mock_ctypes_cdll_return(self, libname): # noqa: ARG002
221+
"""
222+
Mock ctypes.CDLL to count how many times the function is called.
223+
224+
If ctypes.CDLL is called, the counter increases by one.
225+
"""
226+
self.counter += 1 # Increase the counter
227+
return self.loaded_libgmt
228+
229+
@pytest.fixture()
230+
def _mock_ctypes(self, monkeypatch):
231+
monkeypatch.setattr(ctypes, "CDLL", self._mock_ctypes_cdll_return)
232+
233+
@pytest.mark.usefixtures("_mock_ctypes")
234+
def test_libgmt_load_counter(self):
235+
"""
236+
Make sure that the GMT library is not loaded in every session.
237+
"""
238+
with Session() as lib:
239+
_ = lib
240+
with Session() as lib:
241+
_ = lib
242+
assert self.counter == 0 # ctypes.CDLL is not called after two sessions.
243+
244+
# Explicitly calling load_libgmt to make sure the mock function is correct
245+
load_libgmt()
246+
assert self.counter == 1
247+
load_libgmt()
248+
assert self.counter == 2
249+
250+
211251
###############################################################################
212252
# Test clib_full_names
213253
@pytest.fixture(scope="module", name="gmt_lib_names")

0 commit comments

Comments
 (0)