diff --git a/analyzer.go b/analyzer.go new file mode 100644 index 0000000..d25d07a --- /dev/null +++ b/analyzer.go @@ -0,0 +1,42 @@ +package oaichecker + +import ( + "errors" + "fmt" + "net/http" + + "github.com/go-openapi/analysis" +) + +type Analyzer struct { + analyzer *analysis.Spec +} + +func NewAnalyzer(specs *Specs) *Analyzer { + if specs == nil { + return &Analyzer{} + } + + return &Analyzer{ + analyzer: analysis.New(specs.document.OrigSpec()), + } +} + +func (t *Analyzer) Analyze(req *http.Request) error { + if t.analyzer == nil { + return errors.New("no specs defined") + } + + if req == nil { + return errors.New("no request defined") + } + + operation, ok := t.analyzer.OperationFor(req.Method, req.URL.Path) + if !ok { + return errors.New("operation not defined inside the specs") + } + + fmt.Printf("operation: %#v\n", operation) + + return nil +} diff --git a/analyzer_test.go b/analyzer_test.go new file mode 100644 index 0000000..b9851ad --- /dev/null +++ b/analyzer_test.go @@ -0,0 +1,42 @@ +package oaichecker + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_Analyzer_Analyze_with_no_specs(t *testing.T) { + analyzer := NewAnalyzer(nil) + + err := analyzer.Analyze(nil) + + assert.EqualError(t, err, "no specs defined") +} + +func Test_Analyzer_Analyze_with_no_request(t *testing.T) { + specs, err := NewSpecsFromFile("./dataset/petstore_minimal.json") + require.NoError(t, err) + + analyzer := NewAnalyzer(specs) + + err = analyzer.Analyze(nil) + + assert.EqualError(t, err, "no request defined") +} + +func Test_Analyzer_Analyze_with_request_not_in_specs(t *testing.T) { + specs, err := NewSpecsFromFile("./dataset/petstore_minimal.json") + require.NoError(t, err) + + analyzer := NewAnalyzer(specs) + + req, err := http.NewRequest("GET", "invalid/path", nil) + require.NoError(t, err) + + err = analyzer.Analyze(req) + + assert.EqualError(t, err, "operation not defined inside the specs") +}