|
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
14 | 14 | import logging |
| 15 | +import re |
15 | 16 |
|
16 | 17 | import pytest |
17 | 18 | from sqlalchemy import create_engine |
18 | 19 |
|
19 | 20 | from opentelemetry import context |
20 | 21 | from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor |
| 22 | +from opentelemetry.semconv.trace import SpanAttributes |
21 | 23 | from opentelemetry.test.test_base import TestBase |
22 | 24 |
|
23 | 25 |
|
@@ -56,6 +58,38 @@ def test_sqlcommenter_enabled(self): |
56 | 58 | r"SELECT 1 /\*db_driver='(.*)',traceparent='\d{1,2}-[a-zA-Z0-9_]{32}-[a-zA-Z0-9_]{16}-\d{1,2}'\*/;", |
57 | 59 | ) |
58 | 60 |
|
| 61 | + def test_sqlcommenter_enabled_matches_db_statement_attribute(self): |
| 62 | + engine = create_engine("sqlite:///:memory:") |
| 63 | + SQLAlchemyInstrumentor().instrument( |
| 64 | + engine=engine, |
| 65 | + tracer_provider=self.tracer_provider, |
| 66 | + enable_commenter=True, |
| 67 | + commenter_options={"db_framework": False}, |
| 68 | + ) |
| 69 | + cnx = engine.connect() |
| 70 | + cnx.execute("SELECT 1;").fetchall() |
| 71 | + query_log = self.caplog.records[-2].getMessage() |
| 72 | + self.assertRegex( |
| 73 | + query_log, |
| 74 | + r"SELECT 1 /\*db_driver='(.*)',traceparent='\d{1,2}-[a-zA-Z0-9_]{32}-[a-zA-Z0-9_]{16}-\d{1,2}'\*/;", |
| 75 | + ) |
| 76 | + spans = self.memory_exporter.get_finished_spans() |
| 77 | + self.assertEqual(len(spans), 2) |
| 78 | + # first span is connection to db |
| 79 | + self.assertEqual(spans[0].name, "connect") |
| 80 | + # second span is query itself |
| 81 | + query_span = spans[1] |
| 82 | + self.assertRegex( |
| 83 | + query_span.attributes[SpanAttributes.DB_STATEMENT], |
| 84 | + r"SELECT 1 /\*db_driver='(.*)',traceparent='\d{1,2}-[a-zA-Z0-9_]{32}-[a-zA-Z0-9_]{16}-\d{1,2}'\*/;", |
| 85 | + ) |
| 86 | + cnx_span_id = re.search(r"[a-zA-Z0-9_]{16}", query_log).group() |
| 87 | + db_statement_span_id = re.search( |
| 88 | + r"[a-zA-Z0-9_]{16}", |
| 89 | + query_span.attributes[SpanAttributes.DB_STATEMENT], |
| 90 | + ).group() |
| 91 | + self.assertEqual(cnx_span_id, db_statement_span_id) |
| 92 | + |
59 | 93 | def test_sqlcommenter_enabled_otel_values_false(self): |
60 | 94 | engine = create_engine("sqlite:///:memory:") |
61 | 95 | SQLAlchemyInstrumentor().instrument( |
|
0 commit comments