Skip to content

Commit 92a103d

Browse files
committed
Add FindTestVar helper function
1 parent 290bc22 commit 92a103d

2 files changed

Lines changed: 34 additions & 2 deletions

File tree

README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,11 +73,17 @@ func (code *Code) Assignment(a *AssignmentArgs) *Code
7373
func (code *Code) CompositeLit(LiteralType string) *Code
7474
func (code *Code) ShortVarDecl(a *ShortVarDeclArgs) *Code
7575
func (code *Code) KeyedElement(a *KeyedElementArgs) *Code
76-
func (code *Code) TestVarDecl(tv []TestVar) *Code
7776
func (code *Code) Format() error
7877
func (code *Code) String() string
7978
```
8079

80+
The package includes support for generating test variable declarations through the TestVarDecl method. Test variables are predefined values with associated types and names that can be reused across multiple test cases to ensure consistency. The FindTestVar helper function allows you to retrieve a specific test variable by its type from an array of TestVar structs.
81+
82+
```go
83+
func (code *Code) TestVarDecl(tv []TestVar) *Code
84+
func FindTestVar(t string, tv []TestVar) (*TestVar, error)
85+
```
86+
8187
## Example
8288

8389
```go

testvar.go

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@
33
// that can be found in the LICENSE file.
44
package lpcode
55

6-
import "fmt"
6+
import (
7+
"fmt" // fmt
8+
9+
"github.com/thorsphere/tserr" // tserr
10+
)
711

812
type TestVar struct {
913
T string // type of testvariable
@@ -43,3 +47,25 @@ func (code *Code) TestVarDecl(tv []TestVar) *Code {
4347
// Return generated code
4448
return code
4549
}
50+
51+
// findTestVar is a helper function that takes t as a string representing a type, iterates
52+
// through the array of TestVar structs tv, and checks if the type of any TestVar matches t.
53+
// It returns a pointer to the corresponding TestVar struct for that type.
54+
// It returns nil and an error if the type is not found in the predefined test cases
55+
// or if there is an issue with the input.
56+
func FindTestVar(t string, tv []TestVar) (*TestVar, error) {
57+
// Return nil and an error in case tv is nil
58+
if tv == nil {
59+
return nil, tserr.NilPtr()
60+
}
61+
// Iterate over testvars and return the one that matches the type t
62+
for _, v := range tv {
63+
// Check if the type of the current TestVar matches t
64+
if v.T == t {
65+
// If a match is found, return a pointer to the corresponding TestVar struct
66+
return &v, nil
67+
}
68+
}
69+
// Return nil and an error if the type is not found in the predefined test variables
70+
return nil, tserr.NotExistent(fmt.Sprintf("test variable of type %v", t))
71+
}

0 commit comments

Comments
 (0)