Skip to content

Commit d63df93

Browse files
authored
Add OpenAI Mock Server (#31)
* add constants for completions, refactor usage, add test server Signed-off-by: Oleg <[email protected]> * append v1 endpoint to test Signed-off-by: Oleg <[email protected]> * add makefile for easy targets Signed-off-by: Oleg <[email protected]> * lint files & add linter Signed-off-by: Oleg <[email protected]> * disable real API tests in short mode Signed-off-by: Oleg <[email protected]> Signed-off-by: Oleg <[email protected]>
1 parent 8b463ce commit d63df93

File tree

12 files changed

+619
-61
lines changed

12 files changed

+619
-61
lines changed

.golangci.yml

Lines changed: 275 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,275 @@
1+
## Golden config for golangci-lint v1.47.3
2+
#
3+
# This is the best config for golangci-lint based on my experience and opinion.
4+
# It is very strict, but not extremely strict.
5+
# Feel free to adopt and change it for your needs.
6+
7+
run:
8+
# Timeout for analysis, e.g. 30s, 5m.
9+
# Default: 1m
10+
timeout: 3m
11+
12+
13+
# This file contains only configs which differ from defaults.
14+
# All possible options can be found here https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml
15+
linters-settings:
16+
cyclop:
17+
# The maximal code complexity to report.
18+
# Default: 10
19+
max-complexity: 30
20+
# The maximal average package complexity.
21+
# If it's higher than 0.0 (float) the check is enabled
22+
# Default: 0.0
23+
package-average: 10.0
24+
25+
errcheck:
26+
# Report about not checking of errors in type assertions: `a := b.(MyStruct)`.
27+
# Such cases aren't reported by default.
28+
# Default: false
29+
check-type-assertions: true
30+
31+
funlen:
32+
# Checks the number of lines in a function.
33+
# If lower than 0, disable the check.
34+
# Default: 60
35+
lines: 100
36+
# Checks the number of statements in a function.
37+
# If lower than 0, disable the check.
38+
# Default: 40
39+
statements: 50
40+
41+
gocognit:
42+
# Minimal code complexity to report
43+
# Default: 30 (but we recommend 10-20)
44+
min-complexity: 20
45+
46+
gocritic:
47+
# Settings passed to gocritic.
48+
# The settings key is the name of a supported gocritic checker.
49+
# The list of supported checkers can be find in https://go-critic.github.io/overview.
50+
settings:
51+
captLocal:
52+
# Whether to restrict checker to params only.
53+
# Default: true
54+
paramsOnly: false
55+
underef:
56+
# Whether to skip (*x).method() calls where x is a pointer receiver.
57+
# Default: true
58+
skipRecvDeref: false
59+
60+
gomnd:
61+
# List of function patterns to exclude from analysis.
62+
# Values always ignored: `time.Date`
63+
# Default: []
64+
ignored-functions:
65+
- os.Chmod
66+
- os.Mkdir
67+
- os.MkdirAll
68+
- os.OpenFile
69+
- os.WriteFile
70+
- prometheus.ExponentialBuckets
71+
- prometheus.ExponentialBucketsRange
72+
- prometheus.LinearBuckets
73+
- strconv.FormatFloat
74+
- strconv.FormatInt
75+
- strconv.FormatUint
76+
- strconv.ParseFloat
77+
- strconv.ParseInt
78+
- strconv.ParseUint
79+
80+
gomodguard:
81+
blocked:
82+
# List of blocked modules.
83+
# Default: []
84+
modules:
85+
- github.com/golang/protobuf:
86+
recommendations:
87+
- google.golang.org/protobuf
88+
reason: "see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules"
89+
- github.com/satori/go.uuid:
90+
recommendations:
91+
- github.com/google/uuid
92+
reason: "satori's package is not maintained"
93+
- github.com/gofrs/uuid:
94+
recommendations:
95+
- github.com/google/uuid
96+
reason: "see recommendation from dev-infra team: https://confluence.gtforge.com/x/gQI6Aw"
97+
98+
govet:
99+
# Enable all analyzers.
100+
# Default: false
101+
enable-all: true
102+
# Disable analyzers by name.
103+
# Run `go tool vet help` to see all analyzers.
104+
# Default: []
105+
disable:
106+
- fieldalignment # too strict
107+
# Settings per analyzer.
108+
settings:
109+
shadow:
110+
# Whether to be strict about shadowing; can be noisy.
111+
# Default: false
112+
strict: true
113+
114+
nakedret:
115+
# Make an issue if func has more lines of code than this setting, and it has naked returns.
116+
# Default: 30
117+
max-func-lines: 0
118+
119+
nolintlint:
120+
# Exclude following linters from requiring an explanation.
121+
# Default: []
122+
allow-no-explanation: [ funlen, gocognit, lll ]
123+
# Enable to require an explanation of nonzero length after each nolint directive.
124+
# Default: false
125+
require-explanation: true
126+
# Enable to require nolint directives to mention the specific linter being suppressed.
127+
# Default: false
128+
require-specific: true
129+
130+
rowserrcheck:
131+
# database/sql is always checked
132+
# Default: []
133+
packages:
134+
- github.com/jmoiron/sqlx
135+
136+
tenv:
137+
# The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures.
138+
# Otherwise, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked.
139+
# Default: false
140+
all: true
141+
142+
varcheck:
143+
# Check usage of exported fields and variables.
144+
# Default: false
145+
exported-fields: false # default false # TODO: enable after fixing false positives
146+
147+
148+
linters:
149+
disable-all: true
150+
enable:
151+
## enabled by default
152+
- deadcode # Finds unused code
153+
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
154+
- gosimple # Linter for Go source code that specializes in simplifying a code
155+
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
156+
- ineffassign # Detects when assignments to existing variables are not used
157+
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
158+
- structcheck # Finds unused struct fields
159+
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
160+
- unused # Checks Go code for unused constants, variables, functions and types
161+
- varcheck # Finds unused global variables and constants
162+
## disabled by default
163+
# - asasalint # Check for pass []any as any in variadic func(...any)
164+
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
165+
- bidichk # Checks for dangerous unicode character sequences
166+
- bodyclose # checks whether HTTP response body is closed successfully
167+
- contextcheck # check the function whether use a non-inherited context
168+
- cyclop # checks function and package cyclomatic complexity
169+
- dupl # Tool for code clone detection
170+
- durationcheck # check for two durations multiplied together
171+
- errname # Checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error.
172+
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
173+
- execinquery # execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds
174+
- exhaustive # check exhaustiveness of enum switch statements
175+
- exportloopref # checks for pointers to enclosing loop variables
176+
- forbidigo # Forbids identifiers
177+
- funlen # Tool for detection of long functions
178+
# - gochecknoglobals # check that no global variables exist
179+
- gochecknoinits # Checks that no init functions are present in Go code
180+
- gocognit # Computes and checks the cognitive complexity of functions
181+
- goconst # Finds repeated strings that could be replaced by a constant
182+
- gocritic # Provides diagnostics that check for bugs, performance and style issues.
183+
- gocyclo # Computes and checks the cyclomatic complexity of functions
184+
- godot # Check if comments end in a period
185+
- goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt.
186+
- gomnd # An analyzer to detect magic numbers.
187+
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
188+
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
189+
- goprintffuncname # Checks that printf-like functions are named with f at the end
190+
- gosec # Inspects source code for security problems
191+
- lll # Reports long lines
192+
- makezero # Finds slice declarations with non-zero initial length
193+
# - nakedret # Finds naked returns in functions greater than a specified function length
194+
- nestif # Reports deeply nested if statements
195+
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
196+
- nilnil # Checks that there is no simultaneous return of nil error and an invalid value.
197+
# - noctx # noctx finds sending http request without context.Context
198+
- nolintlint # Reports ill-formed or insufficient nolint directives
199+
# - nonamedreturns # Reports all named returns
200+
- nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL.
201+
- predeclared # find code that shadows one of Go's predeclared identifiers
202+
- promlinter # Check Prometheus metrics naming via promlint
203+
- revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint.
204+
- rowserrcheck # checks whether Err of rows is checked successfully
205+
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
206+
- stylecheck # Stylecheck is a replacement for golint
207+
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
208+
- testpackage # linter that makes you use a separate _test package
209+
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
210+
- unconvert # Remove unnecessary type conversions
211+
- unparam # Reports unused function parameters
212+
- wastedassign # wastedassign finds wasted assignment statements.
213+
- whitespace # Tool for detection of leading and trailing whitespace
214+
## you may want to enable
215+
#- decorder # check declaration order and count of types, constants, variables and functions
216+
#- exhaustruct # Checks if all structure fields are initialized
217+
#- goheader # Checks is file header matches to pattern
218+
#- ireturn # Accept Interfaces, Return Concrete Types
219+
#- prealloc # [premature optimization, but can be used in some cases] Finds slice declarations that could potentially be preallocated
220+
#- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope
221+
#- wrapcheck # Checks that errors returned from external packages are wrapped
222+
## disabled
223+
#- containedctx # containedctx is a linter that detects struct contained context.Context field
224+
#- depguard # [replaced by gomodguard] Go linter that checks if package imports are in a list of acceptable packages
225+
#- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
226+
#- errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/errchkjson] Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted.
227+
#- forcetypeassert # [replaced by errcheck] finds forced type assertions
228+
#- gci # Gci controls golang package import order and makes it always deterministic.
229+
#- godox # Tool for detection of FIXME, TODO and other comment keywords
230+
#- goerr113 # [too strict] Golang linter to check the errors handling expressions
231+
#- gofmt # [replaced by goimports] Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
232+
#- gofumpt # [replaced by goimports, gofumports is not available yet] Gofumpt checks whether code was gofumpt-ed.
233+
#- grouper # An analyzer to analyze expression groups.
234+
#- ifshort # Checks that your code uses short syntax for if-statements whenever possible
235+
#- importas # Enforces consistent import aliases
236+
#- maintidx # maintidx measures the maintainability index of each function.
237+
#- misspell # [useless] Finds commonly misspelled English words in comments
238+
#- nlreturn # [too strict and mostly code is not more readable] nlreturn checks for a new line before return and branch statements to increase code clarity
239+
#- nosnakecase # Detects snake case of variable naming and function name. # TODO: maybe enable after https://github.com/sivchari/nosnakecase/issues/14
240+
#- paralleltest # [too many false positives] paralleltest detects missing usage of t.Parallel() method in your Go test
241+
#- tagliatelle # Checks the struct tags.
242+
#- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
243+
#- wsl # [too strict and mostly code is not more readable] Whitespace Linter - Forces you to use empty lines!
244+
## deprecated
245+
#- exhaustivestruct # [deprecated, replaced by exhaustruct] Checks if all struct's fields are initialized
246+
#- golint # [deprecated, replaced by revive] Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
247+
#- interfacer # [deprecated] Linter that suggests narrower interface types
248+
#- maligned # [deprecated, replaced by govet fieldalignment] Tool to detect Go structs that would take less memory if their fields were sorted
249+
#- scopelint # [deprecated, replaced by exportloopref] Scopelint checks for unpinned variables in go programs
250+
251+
252+
issues:
253+
# Maximum count of issues with the same text.
254+
# Set to 0 to disable.
255+
# Default: 3
256+
max-same-issues: 50
257+
258+
exclude-rules:
259+
- source: "^//\\s*go:generate\\s"
260+
linters: [ lll ]
261+
- source: "(noinspection|TODO)"
262+
linters: [ godot ]
263+
- source: "//noinspection"
264+
linters: [ gocritic ]
265+
- source: "^\\s+if _, ok := err\\.\\([^.]+\\.InternalError\\); ok {"
266+
linters: [ errorlint ]
267+
- path: "_test\\.go"
268+
linters:
269+
- bodyclose
270+
- dupl
271+
- funlen
272+
- goconst
273+
- gosec
274+
- noctx
275+
- wrapcheck

Makefile

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
##@ General
2+
3+
# The help target prints out all targets with their descriptions organized
4+
# beneath their categories. The categories are represented by '##@' and the
5+
# target descriptions by '##'. The awk commands is responsible for reading the
6+
# entire set of makefiles included in this invocation, looking for lines of the
7+
# file as xyz: ## something, and then pretty-format the target and help. Then,
8+
# if there's a line with ##@ something, that gets pretty-printed as a category.
9+
# More info on the usage of ANSI control characters for terminal formatting:
10+
# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters
11+
# More info on the awk command:
12+
# http://linuxcommand.org/lc3_adv_awk.php
13+
14+
.PHONY: help
15+
help: ## Display this help.
16+
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)
17+
18+
19+
##@ Development
20+
21+
.PHONY: test
22+
TEST_ARGS ?= -v
23+
TEST_TARGETS ?= ./...
24+
test: ## Test the Go modules within this package.
25+
@ echo ▶️ go test $(TEST_ARGS) $(TEST_TARGETS)
26+
go test $(TEST_ARGS) $(TEST_TARGETS)
27+
@ echo ✅ success!
28+
29+
30+
.PHONY: lint
31+
LINT_TARGETS ?= ./...
32+
lint: ## Lint Go code with the installed golangci-lint
33+
@ echo "▶️ golangci-lint run"
34+
golangci-lint run $(LINT_TARGETS)
35+
@ echo "✅ golangci-lint run"

api.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,15 @@ func newTransport() *http.Client {
1515
}
1616
}
1717

18-
// Client is OpenAI GPT-3 API client
18+
// Client is OpenAI GPT-3 API client.
1919
type Client struct {
2020
BaseURL string
2121
HTTPClient *http.Client
2222
authToken string
2323
idOrg string
2424
}
2525

26-
// NewClient creates new OpenAI API client
26+
// NewClient creates new OpenAI API client.
2727
func NewClient(authToken string) *Client {
2828
return &Client{
2929
BaseURL: apiURLv1,
@@ -33,7 +33,7 @@ func NewClient(authToken string) *Client {
3333
}
3434
}
3535

36-
// NewOrgClient creates new OpenAI API client for specified Organization ID
36+
// NewOrgClient creates new OpenAI API client for specified Organization ID.
3737
func NewOrgClient(authToken, org string) *Client {
3838
return &Client{
3939
BaseURL: apiURLv1,

0 commit comments

Comments
 (0)