test: improve code coverage with comprehensive unit tests#323
test: improve code coverage with comprehensive unit tests#323dlevy-msft-sql wants to merge 2 commits intomicrosoft:mainfrom
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #323 +/- ##
===========================================
+ Coverage 78.59% 96.60% +18.00%
===========================================
Files 34 89 +55
Lines 6598 74007 +67409
===========================================
+ Hits 5186 71497 +66311
- Misses 1134 2173 +1039
- Partials 278 337 +59
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Pull request overview
This PR substantially increases unit and integration test coverage across the driver, networking, encryption, authentication, and Always Encrypted code paths, and wires coverage reporting into CI via Codecov.
Changes:
- Add extensive unit tests for core conversion, type metadata, encryption/AE pipeline, GUID handling, error types, and protocol helpers (e.g.,
convertAssign, AE CEK/parameter structs,makeGoLangScanType,buildStoredProcedureStatementForColumnEncryption). - Add focused tests for network abstractions (
timeoutConn,tlsHandshakeConn,passthroughConn), browser/protocol utilities, integrated authentication (NTLM/Kerberos/channel binding), and Azure AD / access-token connectors, plus corresponding integration tests gated on environment. - Update CI to collect coverage (
go test -coverprofile) and upload to Codecov, with a newcodecov.ymlenforcing an 80% project and patch coverage target.
Reviewed changes
Copilot reviewed 44 out of 45 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
uniqueidentifier_test.go |
Adds negative tests for UniqueIdentifier.UnmarshalJSON and Scan invalid input cases, strengthening GUID parsing validation. |
uniqueidentifier_null_test.go |
Adds a happy-path NullUniqueIdentifier.MarshalJSON test ensuring non-empty output for valid UUIDs. |
types_test.go |
Refactors and expands tests for type-to-Go mappings (makeGoLangScanType, makeGoLangTypeName, makeGoLangTypeLength, makeGoLangTypePrecisionScale, makeDecl) into table-driven coverage across many TDS types. |
token_unit_test.go |
Adds unit tests for RWCBuffer read/write/close semantics and multi-read behavior, validating its use in decryption flows. |
token_test.go |
Adds tests for doneStruct.isError() and doneStruct.getError() behavior, including default message and aggregation of multiple errors. |
timezone_test.go |
Verifies getTimezone behavior for nil/partial connections and non-UTC locations via msdsn.EncodeParameters. |
tds_unit_test.go |
Tests browser/DAC parsing helpers (parseDAC, parseInstances), UTF-16 conversion (str2ucs2), password mangling, encryption flags, key sorting, feature extension structures, and type info helpers like columnStruct.originalTypeInfo. |
tds_test.go |
Makes TestLeakedConnections more robust by retrying the connection-count query with short sleeps before asserting no leaks. |
tds_go113_test.go |
Relaxes TestConnectError to accept both timeout and non-timeout dial errors depending on environment, logging instead of failing. |
rowsq_unit_test.go |
Adds tests for Rowsq column metadata methods (ColumnTypeScanType, ColumnTypeDatabaseTypeName/Length/PrecisionScale/Nullable) ensuring they reflect underlying typeInfo. |
quoter_test.go |
Adds comprehensive tests for TSQLQuoter.ID, TSQLQuoter.Value, panic cases for unsupported types, and sqlString escaping, covering identifier and literal quoting including SQL injection-like inputs. |
protocol_unit_test.go |
Tests stringForInstanceNameComparison, resolveServerPort, and wrapConnErr including error wrapping and error unwrapping semantics. |
net_test.go |
Extends tests for tlsHandshakeConn.FinishPacket, and adds unit tests for timeoutConn, tlsHandshakeConn lifecycle and deadlines, and passthroughConn delegation to an underlying net.Conn. |
net_integration_test.go |
Integration tests verifying NewConnector and timeoutConn usage over real connections, including TLS handshake scenarios, gated by connection string availability. |
mssql_go110_unit_test.go |
Adds tests for Result.LastInsertId error messaging, Connector.Driver, Conn.ResetSession, CEK provider registration, bulk operations (CreateBulk, CopyIn), NewConnectorWithAccessTokenProvider, and Driver.OpenConnection error paths. |
mssql_go110_integration_test.go |
Integration tests for connector-based connections, ResetSession (with and without SessionInitSQL), sql.OpenDB(connector), and multiple connections from a single connector, conditioned on SQL Server availability. |
msdsn/conn_str_test.go |
Adds tests for EncodeParameters.GetTimezone (nil vs specific location) and Config.URL across several host/port/instance combinations. |
internal/github.com/swisscom/mssql-always-encrypted/pkg/utils/utils_test.go |
Tests UTF-16LE conversion helpers used for key derivation salts and encoding. |
internal/github.com/swisscom/mssql-always-encrypted/pkg/keys/keys_test.go |
Validates derived key lengths, distinctness between encryption/MAC/IV keys, determinism w.r.t. root key, and Key interface implementation. |
internal/github.com/swisscom/mssql-always-encrypted/pkg/encryption/encryption_test.go |
Verifies encryption Type values (Plaintext, Deterministic, Randomized) and From mapping semantics including unknown values. |
internal/github.com/swisscom/mssql-always-encrypted/pkg/crypto/crypto_test.go |
Adds tests for AES-CBC/PKCS5 construction, encrypt/decrypt round-trips, PKCS5 padding/trim, and ciphertext variability with different keys. |
internal/github.com/swisscom/mssql-always-encrypted/pkg/algorithms/algorithms_additional_test.go |
Extends AEAD AES-256-CBC-HMAC-SHA256 tests for deterministic vs randomized modes, error conditions (length/version/auth tag), and round-trips over varied plaintexts. |
internal/cp/cp_test.go |
Adds tests for collation LCID/flags/version extraction, collation-to-charset mapping, CharsetToUTF8 across key code pages, and code page getter sanity. |
integratedauth/ntlm/ntlm_test.go |
Adds UTF-16LE conversion tests, Auth lifecycle and channel-binding behavior, getAuth parsing of domain\user, NTLM response building, and NextBytes validation for malformed and valid challenge messages. |
integratedauth/krb5/krb5_test.go |
Tests canonicalize robustness, krbAuth.Free with nil client, and fileExistsOS behavior for missing config files. |
integratedauth/channel_binding_test.go |
Adds detailed tests around generating and hashing channel bindings from TLS unique/exporter values and server certs, ChannelBindings→SEC_CHANNEL_BINDINGS conversions, and empty-binding behavior. |
fedauth_test.go |
Adds constant-value tests for fedauth enums and constructor tests for security-token and ADAL connectors, including nil provider validation, error propagation, and parameter passing to token providers. |
fedauth_integration_test.go |
Integration scaffolding for fedauth, including Azure SQL-specific connector configuration tests and examples for sql.OpenDB usage, most of which are skipped without appropriate environment. |
error_test.go |
Adds tests covering Error string formatting and SQL-specific accessors (SQLErrorNumber/State/Class/...). |
encrypt_unit_test.go |
Adds tests for ColumnEncryptionType values, AE metadata structs (cekData, parameterEncData, paramMapEntry), parameter name prefixing, sproc statement generation, and basic prepareEncryptionQuery behavior. |
encrypt_integration_test.go |
Integration tests exercising prepared statements, stored procedures, quoted identifiers/values, named parameters, and simple expression-based “output” behavior over a real connection. |
convert_test.go |
Comprehensive tests for convertAssign, cloneBytes, asString, and asBytes across strings, byte slices, numerics, bools, time, nil, interfaces, pointers, and error cases. |
columnencryptionkey_test.go |
Tests newCekTable creation semantics (length, capacity, zero-initialization) across several table sizes. |
codecov.yml |
Introduces Codecov configuration enforcing 80% project and patch coverage, with strict (0%) allowed threshold and tailored comment behavior. |
azuread/driver_unit_test.go |
Adds tests to validate Azure AD driver registration (DriverName) and NewConnector behavior for various DSN and fedauth combinations. |
aecmk/localcert/keyprovider_unit_test.go |
Adds tests for local certificate AE key provider validation logic, password handling, error paths, and allowed-location enforcement. |
aecmk/localcert/keyprovider_go117_windows_test.go |
Adjusts Windows cert-store integration tests to skip gracefully when certificate provisioning fails instead of hard-failing. |
aecmk/aecmk_test.go |
Adds tests for AE CMK provider error types, CEK caching (CekProvider), key lifetimes, provider registration, and global provider retrieval. |
accesstokenconnector_test.go |
Extends tests for NewAccessTokenConnector to cover token-provider invocation, invalid DSNs, and previous failure-path behavior. |
.github/workflows/pr-validation.yml |
Changes PR validation to run go test -coverprofile=coverage.out -covermode=atomic ./... and upload coverage via codecov/codecov-action@v4 using CODECOV_TOKEN. |
|
@copilot use |
Done. Dave-pilot out. 🤣 |
5fc50fc to
10290b0
Compare
10290b0 to
b5470aa
Compare
# Conflicts: # convert_test.go
Summary
This PR adds comprehensive unit tests to improve code coverage, working toward the 80%+ threshold for awesome-go inclusion.
Changes
New Test Files
types_unit_test.go: Extensive tests for type conversion functions that don't require SQL Server
protocol_unit_test.go: Tests for protocol helper functions
timezone_test.go: Tests for timezone handling
Enhanced Existing Tests
Coverage Impact
These tests focus on pure functions that can be tested without SQL Server connections, providing reliable coverage that will pass in CI environments.
Unit tests alone now contribute ~27% coverage (up from ~3%), and combined with integration tests we're seeing 79.2% coverage locally.
Testing
All new tests pass locally: