Skip to content

test: improve code coverage with comprehensive unit tests#323

Open
dlevy-msft-sql wants to merge 2 commits intomicrosoft:mainfrom
dlevy-msft-sql:coverage-improvements
Open

test: improve code coverage with comprehensive unit tests#323
dlevy-msft-sql wants to merge 2 commits intomicrosoft:mainfrom
dlevy-msft-sql:coverage-improvements

Conversation

@dlevy-msft-sql
Copy link

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

    • DateTime encoding/decoding (decodeDateTim4, encodeDateTim4, decodeDateTime, encodeDateTime)
    • Money decoding (decodeMoney, decodeMoney4)
    • GUID decoding with byte order conversion
    • Date encoding/decoding (decodeDateInt, decodeDate, encodeDate)
    • DateTime2 encoding/decoding with roundtrip tests
    • DateTimeOffset encoding/decoding with timezone preservation
    • Time encoding/decoding (decodeTime, encodeTime, decodeTimeInt)
    • Decimal decoding (decodeDecimal)
    • UCS-2 string decoding (decodeUcs2, decodeNChar)
    • XML and UDT type handling
  • protocol_unit_test.go: Tests for protocol helper functions

    • stringForInstanceNameComparison (instance name normalization)
    • resolveServerPort (default port handling)
  • timezone_test.go: Tests for timezone handling

    • getTimezone function with various location scenarios

Enhanced Existing Tests

  • token_test.go: Added tests for doneStruct.isError() and getError()
  • accesstokenconnector_test.go: Added test for invalid DSN error path
  • uniqueidentifier_test.go: Added edge case tests for Scan and MarshalJSON
  • types_test.go: Expanded coverage for type functions

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:

go test -run "TestDecode|TestEncode|TestThreeHundredths|TestGregorianDays|TestMoney|TestGuid|TestCalcTimeSize|TestDateTime2|TestDecimal|TestUcs2|TestNChar|TestUdt|TestXml" -v

@dlevy-msft-sql dlevy-msft-sql marked this pull request as draft February 4, 2026 05:35
@codecov-commenter
Copy link

codecov-commenter commented Feb 4, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.60%. Comparing base (95e5e8a) to head (6dd351d).

Additional details and impacted files

Impacted file tree graph

@@             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     
Flag Coverage Δ
unittests 96.54% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.
see 62 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@dlevy-msft-sql dlevy-msft-sql marked this pull request as ready for review February 4, 2026 20:39
@dlevy-msft-sql dlevy-msft-sql self-assigned this Feb 4, 2026
@dlevy-msft-sql dlevy-msft-sql added Priority: 1 High priority/impact in-review Size: Jumbo More than 5000 lines of code that cannot be broken up labels Feb 4, 2026
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 new codecov.yml enforcing 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, ChannelBindingsSEC_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.

@shueybubbles
Copy link
Collaborator

@copilot use assert for new test files. Can keep old test patterns in place for test files that existed before this change.

@dlevy-msft-sql
Copy link
Author

@copilot use assert for new test files. Can keep old test patterns in place for test files that existed before this change.

Done. Dave-pilot out. 🤣

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Priority: 1 High priority/impact Size: Jumbo More than 5000 lines of code that cannot be broken up

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants