Skip to content

Commit

Permalink
init: provide a better error message for missing symbols
Browse files Browse the repository at this point in the history
When the there is a difference in versions between build time and
run time libraries for the bindings there might be missing symbols.
So provide a slightly better error message when that happens, as the
usual message is not to clear.

Signed-off-by: Erik Larsson <who+github@cnackers.org>
  • Loading branch information
whooo committed Aug 16, 2023
1 parent 90997f7 commit da193d0
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/tpm2_pytss/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,21 @@
import _cffi_backend

# check that we can load the C bindings,
# if we can't, provide a better message.
try:
from ._libtpm2_pytss import lib
except ImportError as e:
parts = e.msg.split(": ", 2)
if len(parts) != 3:
raise e
path, error, symbol = parts
if error != "undefined symbol":
raise e
raise ImportError(
f"failed to load tpm2-tss bindigs in {path} due to missing symbol {symbol}, "
+ "ensure that you are using the same libraries the python module was built against."
)

from .ESAPI import ESAPI

try:
Expand Down
47 changes: 47 additions & 0 deletions test/test_import.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/python3 -u
# SPDX-License-Identifier: BSD-2

import sys
import unittest


class mocklib:
def __init__(self, msg):
self.msg = msg

@property
def lib(self):
raise ImportError(self.msg)


class ImportTest(unittest.TestCase):
def test_missing_symbol(self):
if "tpm2_pytss" in sys.modules:
del sys.modules["tpm2_pytss"]
sys.modules["tpm2_pytss._libtpm2_pytss"] = mocklib(
"/tmp/tpm2_pytss/_libtpm2_pytss.abi3.so: undefined symbol: test_symbol"
)
with self.assertRaises(ImportError) as e:
import tpm2_pytss
self.assertEqual(
e.exception.msg,
"failed to load tpm2-tss bindigs in /tmp/tpm2_pytss/_libtpm2_pytss.abi3.so"
+ " due to missing symbol test_symbol, ensure that you are using the same"
+ " libraries the python module was built against.",
)

def test_other_message(self):
if "tpm2_pytss" in sys.modules:
del sys.modules["tpm2_pytss"]
sys.modules["tpm2_pytss._libtpm2_pytss"] = mocklib("I am a teapot")
with self.assertRaises(ImportError) as e:
import tpm2_pytss
self.assertEqual(e.exception.msg, "I am a teapot")

def test_not_missing_symbol(self):
if "tpm2_pytss" in sys.modules:
del sys.modules["tpm2_pytss"]
sys.modules["tpm2_pytss._libtpm2_pytss"] = mocklib("/bin/ls: not a: teapot")
with self.assertRaises(ImportError) as e:
import tpm2_pytss
self.assertEqual(e.exception.msg, "/bin/ls: not a: teapot")

0 comments on commit da193d0

Please sign in to comment.