diff --git a/v3/newrelic/transaction.go b/v3/newrelic/transaction.go index ccdf274ac..7d2f8ff76 100644 --- a/v3/newrelic/transaction.go +++ b/v3/newrelic/transaction.go @@ -239,6 +239,16 @@ func (txn *Transaction) SetWebRequestHTTP(r *http.Request) { txn.SetWebRequest(wr) } +// IsEnded returns transaction end status. +// If the transaction is nil, the thread is nil, or the transaction is finished, it returns true. +// Otherwise, it returns thread.finished value. +func (txn *Transaction) IsEnded() bool { + if txn == nil || txn.thread == nil || txn.thread.txn == nil { + return true + } + return txn.thread.txn.finished +} + func transport(r *http.Request) TransportType { if strings.HasPrefix(r.Proto, "HTTP") { if r.TLS != nil { diff --git a/v3/newrelic/transaction_test.go b/v3/newrelic/transaction_test.go index e5dd70f27..d10fc69c8 100644 --- a/v3/newrelic/transaction_test.go +++ b/v3/newrelic/transaction_test.go @@ -6,6 +6,29 @@ import ( "testing" ) +func TestIsEnded(t *testing.T) { + tests := []struct { + name string + txn *Transaction + expected bool + }{ + {"txn is nil", nil, true}, + {"thread is nil", &Transaction{thread: nil}, true}, + {"txn.thread.txn is nil", &Transaction{thread: &thread{}}, true}, + {"txn.thread.txn.finished is true", &Transaction{thread: &thread{txn: &txn{finished: true}}}, true}, + {"txn.thread.txn.finished is false", &Transaction{thread: &thread{txn: &txn{finished: false}}}, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := tt.txn.IsEnded() + if result != tt.expected { + t.Errorf("IsEnded() = %v; want %v", result, tt.expected) + } + }) + } +} + func TestTransaction_MethodsWithNilTransaction(t *testing.T) { var nilTxn *Transaction