|
| 1 | +# Copyright The OpenTelemetry Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import contextlib |
| 16 | + |
| 17 | +from sqlalchemy import Column, Integer, String, create_engine |
| 18 | +from sqlalchemy.ext.declarative import declarative_base |
| 19 | +from sqlalchemy.orm import sessionmaker |
| 20 | + |
| 21 | +from opentelemetry import trace |
| 22 | +from opentelemetry.ext.sqlalchemy import SQLAlchemyInstrumentor |
| 23 | +from opentelemetry.ext.sqlalchemy.engine import _DB, _ROWS, _STMT |
| 24 | +from opentelemetry.test.test_base import TestBase |
| 25 | + |
| 26 | +Base = declarative_base() |
| 27 | + |
| 28 | + |
| 29 | +def _create_engine(engine_args): |
| 30 | + # create a SQLAlchemy engine |
| 31 | + config = dict(engine_args) |
| 32 | + url = config.pop("url") |
| 33 | + return create_engine(url, **config) |
| 34 | + |
| 35 | + |
| 36 | +class Player(Base): |
| 37 | + """Player entity used to test SQLAlchemy ORM""" |
| 38 | + |
| 39 | + __tablename__ = "players" |
| 40 | + |
| 41 | + id = Column(Integer, primary_key=True) |
| 42 | + name = Column(String(20)) |
| 43 | + |
| 44 | + |
| 45 | +class SQLAlchemyTestMixin(TestBase): |
| 46 | + __test__ = False |
| 47 | + |
| 48 | + """SQLAlchemy test mixin that includes a complete set of tests |
| 49 | + that must be executed for different engine. When a new test (or |
| 50 | + a regression test) should be added to SQLAlchemy test suite, a new |
| 51 | + entry must be appended here so that it will be executed for all |
| 52 | + available and supported engines. If the test is specific to only |
| 53 | + one engine, that test must be added to the specific `TestCase` |
| 54 | + implementation. |
| 55 | +
|
| 56 | + To support a new engine, create a new `TestCase` that inherits from |
| 57 | + `SQLAlchemyTestMixin` and `TestCase`. Then you must define the following |
| 58 | + static class variables: |
| 59 | + * VENDOR: the database vendor name |
| 60 | + * SQL_DB: the `db.type` tag that we expect (it's the name of the database available in the `.env` file) |
| 61 | + * SERVICE: the service that we expect by default |
| 62 | + * ENGINE_ARGS: all arguments required to create the engine |
| 63 | +
|
| 64 | + To check specific tags in each test, you must implement the |
| 65 | + `check_meta(self, span)` method. |
| 66 | + """ |
| 67 | + |
| 68 | + VENDOR = None |
| 69 | + SQL_DB = None |
| 70 | + SERVICE = None |
| 71 | + ENGINE_ARGS = None |
| 72 | + |
| 73 | + @contextlib.contextmanager |
| 74 | + def connection(self): |
| 75 | + # context manager that provides a connection |
| 76 | + # to the underlying database |
| 77 | + try: |
| 78 | + conn = self.engine.connect() |
| 79 | + yield conn |
| 80 | + finally: |
| 81 | + conn.close() |
| 82 | + |
| 83 | + def check_meta(self, span): |
| 84 | + """function that can be implemented according to the |
| 85 | + specific engine implementation |
| 86 | + """ |
| 87 | + |
| 88 | + def setUp(self): |
| 89 | + super().setUp() |
| 90 | + # create an engine with the given arguments |
| 91 | + self.engine = _create_engine(self.ENGINE_ARGS) |
| 92 | + |
| 93 | + # create the database / entities and prepare a session for the test |
| 94 | + Base.metadata.drop_all(bind=self.engine) |
| 95 | + Base.metadata.create_all(self.engine, checkfirst=False) |
| 96 | + self.session = sessionmaker(bind=self.engine)() |
| 97 | + # trace the engine |
| 98 | + SQLAlchemyInstrumentor().instrument( |
| 99 | + engine=self.engine, tracer_provider=self.tracer_provider |
| 100 | + ) |
| 101 | + self.memory_exporter.clear() |
| 102 | + |
| 103 | + def tearDown(self): |
| 104 | + # pylint: disable=invalid-name |
| 105 | + # clear the database and dispose the engine |
| 106 | + self.session.close() |
| 107 | + Base.metadata.drop_all(bind=self.engine) |
| 108 | + self.engine.dispose() |
| 109 | + SQLAlchemyInstrumentor().uninstrument() |
| 110 | + super().tearDown() |
| 111 | + |
| 112 | + def _check_span(self, span): |
| 113 | + self.assertEqual(span.name, "{}.query".format(self.VENDOR)) |
| 114 | + self.assertEqual(span.attributes.get("service"), self.SERVICE) |
| 115 | + self.assertEqual(span.attributes.get(_DB), self.SQL_DB) |
| 116 | + self.assertIs( |
| 117 | + span.status.canonical_code, trace.status.StatusCanonicalCode.OK |
| 118 | + ) |
| 119 | + self.assertGreater((span.end_time - span.start_time), 0) |
| 120 | + |
| 121 | + def test_orm_insert(self): |
| 122 | + # ensures that the ORM session is traced |
| 123 | + wayne = Player(id=1, name="wayne") |
| 124 | + self.session.add(wayne) |
| 125 | + self.session.commit() |
| 126 | + |
| 127 | + spans = self.memory_exporter.get_finished_spans() |
| 128 | + self.assertEqual(len(spans), 1) |
| 129 | + span = spans[0] |
| 130 | + self._check_span(span) |
| 131 | + self.assertIn("INSERT INTO players", span.attributes.get(_STMT)) |
| 132 | + self.assertEqual(span.attributes.get(_ROWS), 1) |
| 133 | + self.check_meta(span) |
| 134 | + |
| 135 | + def test_session_query(self): |
| 136 | + # ensures that the Session queries are traced |
| 137 | + out = list(self.session.query(Player).filter_by(name="wayne")) |
| 138 | + self.assertEqual(len(out), 0) |
| 139 | + |
| 140 | + spans = self.memory_exporter.get_finished_spans() |
| 141 | + self.assertEqual(len(spans), 1) |
| 142 | + span = spans[0] |
| 143 | + self._check_span(span) |
| 144 | + self.assertIn( |
| 145 | + "SELECT players.id AS players_id, players.name AS players_name \nFROM players \nWHERE players.name", |
| 146 | + span.attributes.get(_STMT), |
| 147 | + ) |
| 148 | + self.check_meta(span) |
| 149 | + |
| 150 | + def test_engine_connect_execute(self): |
| 151 | + # ensures that engine.connect() is properly traced |
| 152 | + with self.connection() as conn: |
| 153 | + rows = conn.execute("SELECT * FROM players").fetchall() |
| 154 | + self.assertEqual(len(rows), 0) |
| 155 | + |
| 156 | + spans = self.memory_exporter.get_finished_spans() |
| 157 | + self.assertEqual(len(spans), 1) |
| 158 | + span = spans[0] |
| 159 | + self._check_span(span) |
| 160 | + self.assertEqual(span.attributes.get(_STMT), "SELECT * FROM players") |
| 161 | + self.check_meta(span) |
| 162 | + |
| 163 | + def test_parent(self): |
| 164 | + """Ensure that sqlalchemy works with opentelemetry.""" |
| 165 | + tracer = self.tracer_provider.get_tracer("sqlalch_svc") |
| 166 | + |
| 167 | + with tracer.start_as_current_span("sqlalch_op"): |
| 168 | + with self.connection() as conn: |
| 169 | + rows = conn.execute("SELECT * FROM players").fetchall() |
| 170 | + self.assertEqual(len(rows), 0) |
| 171 | + |
| 172 | + spans = self.memory_exporter.get_finished_spans() |
| 173 | + self.assertEqual(len(spans), 2) |
| 174 | + child_span, parent_span = spans |
| 175 | + |
| 176 | + # confirm the parenting |
| 177 | + self.assertIsNone(parent_span.parent) |
| 178 | + self.assertIs(child_span.parent, parent_span.get_context()) |
| 179 | + |
| 180 | + self.assertEqual(parent_span.name, "sqlalch_op") |
| 181 | + self.assertEqual(parent_span.instrumentation_info.name, "sqlalch_svc") |
| 182 | + |
| 183 | + self.assertEqual(child_span.name, "{}.query".format(self.VENDOR)) |
| 184 | + self.assertEqual(child_span.attributes.get("service"), self.SERVICE) |
0 commit comments