change in Initialse function to read each folder and add test cases
This commit is contained in:
246
plugins/implementations/coverage.html
Normal file
246
plugins/implementations/coverage.html
Normal file
@@ -0,0 +1,246 @@
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>implementations: Go Coverage Report</title>
|
||||
<style>
|
||||
body {
|
||||
background: black;
|
||||
color: rgb(80, 80, 80);
|
||||
}
|
||||
body, pre, #legend span {
|
||||
font-family: Menlo, monospace;
|
||||
font-weight: bold;
|
||||
}
|
||||
#topbar {
|
||||
background: black;
|
||||
position: fixed;
|
||||
top: 0; left: 0; right: 0;
|
||||
height: 42px;
|
||||
border-bottom: 1px solid rgb(80, 80, 80);
|
||||
}
|
||||
#content {
|
||||
margin-top: 50px;
|
||||
}
|
||||
#nav, #legend {
|
||||
float: left;
|
||||
margin-left: 10px;
|
||||
}
|
||||
#legend {
|
||||
margin-top: 12px;
|
||||
}
|
||||
#nav {
|
||||
margin-top: 10px;
|
||||
}
|
||||
#legend span {
|
||||
margin: 0 5px;
|
||||
}
|
||||
.cov0 { color: rgb(192, 0, 0) }
|
||||
.cov1 { color: rgb(128, 128, 128) }
|
||||
.cov2 { color: rgb(116, 140, 131) }
|
||||
.cov3 { color: rgb(104, 152, 134) }
|
||||
.cov4 { color: rgb(92, 164, 137) }
|
||||
.cov5 { color: rgb(80, 176, 140) }
|
||||
.cov6 { color: rgb(68, 188, 143) }
|
||||
.cov7 { color: rgb(56, 200, 146) }
|
||||
.cov8 { color: rgb(44, 212, 149) }
|
||||
.cov9 { color: rgb(32, 224, 152) }
|
||||
.cov10 { color: rgb(20, 236, 155) }
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="topbar">
|
||||
<div id="nav">
|
||||
<select id="files">
|
||||
|
||||
<option value="file0">beckn-onix/plugins/implementations/plugin_impl.go (87.3%)</option>
|
||||
|
||||
</select>
|
||||
</div>
|
||||
<div id="legend">
|
||||
<span>not tracked</span>
|
||||
|
||||
<span class="cov0">not covered</span>
|
||||
<span class="cov8">covered</span>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<div id="content">
|
||||
|
||||
<pre class="file" id="file0" style="display: none">package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"beckn-onix/plugins/definitions"
|
||||
|
||||
"github.com/santhosh-tekuri/jsonschema/v6"
|
||||
)
|
||||
|
||||
// TekuriValidator implements the Validator interface using the santhosh-tekuri/jsonschema package.
|
||||
type TekuriValidator struct {
|
||||
schema *jsonschema.Schema
|
||||
}
|
||||
|
||||
// TekuriValidatorProvider is responsible for managing and providing access to the JSON schema validators.
|
||||
type TekuriValidatorProvider struct {
|
||||
SchemaCache map[string]*jsonschema.Schema
|
||||
}
|
||||
|
||||
// Validate validates the given data against the schema.
|
||||
func (v *TekuriValidator) Validate(ctx context.Context, data []byte) error <span class="cov8" title="1">{
|
||||
var jsonData interface{}
|
||||
if err := json.Unmarshal(data, &jsonData); err != nil </span><span class="cov8" title="1">{
|
||||
return err
|
||||
}</span>
|
||||
<span class="cov8" title="1">err := v.schema.Validate(jsonData)
|
||||
if err != nil </span><span class="cov8" title="1">{
|
||||
// TODO: Integrate with the logging module once it is ready
|
||||
fmt.Printf("Validation error: %v\n", err)
|
||||
}</span>
|
||||
|
||||
<span class="cov8" title="1">return err</span>
|
||||
}
|
||||
|
||||
// Initialize initializes the validator provider by compiling all the JSON schema files
|
||||
// from the specified directory and storing them in a cache. It returns a map of validators
|
||||
// indexed by their schema filenames.
|
||||
func (vp *TekuriValidatorProvider) Initialize(schemaDir string) (map[string]definitions.Validator, error) <span class="cov8" title="1">{
|
||||
// Initialize SchemaCache if it's nil
|
||||
if vp.SchemaCache == nil </span><span class="cov8" title="1">{
|
||||
vp.SchemaCache = make(map[string]*jsonschema.Schema)
|
||||
}</span>
|
||||
// Check if the directory exists and is accessible
|
||||
<span class="cov8" title="1">info, err := os.Stat(schemaDir)
|
||||
if err != nil </span><span class="cov8" title="1">{
|
||||
if os.IsNotExist(err) </span><span class="cov8" title="1">{
|
||||
return nil, fmt.Errorf("schema directory does not exist: %s", schemaDir)
|
||||
}</span>
|
||||
<span class="cov0" title="0">return nil, fmt.Errorf("failed to access schema directory: %v", err)</span>
|
||||
}
|
||||
<span class="cov8" title="1">if !info.IsDir() </span><span class="cov8" title="1">{
|
||||
return nil, fmt.Errorf("provided schema path is not a directory: %s", schemaDir)
|
||||
}</span>
|
||||
|
||||
// Initialize the validatorCache map to store the Validator instances associated with each schema.
|
||||
<span class="cov8" title="1">validatorCache := make(map[string]definitions.Validator)
|
||||
compiler := jsonschema.NewCompiler()
|
||||
|
||||
// Helper function to process directories recursively
|
||||
var processDir func(dir string) error
|
||||
processDir = func(dir string) error </span><span class="cov8" title="1">{
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil </span><span class="cov0" title="0">{
|
||||
return fmt.Errorf("failed to read directory: %v", err)
|
||||
}</span>
|
||||
|
||||
<span class="cov8" title="1">for _, entry := range entries </span><span class="cov8" title="1">{
|
||||
path := filepath.Join(dir, entry.Name())
|
||||
if entry.IsDir() </span><span class="cov8" title="1">{
|
||||
// Recursively process subdirectories
|
||||
if err := processDir(path); err != nil </span><span class="cov8" title="1">{
|
||||
return err
|
||||
}</span>
|
||||
} else<span class="cov8" title="1"> if filepath.Ext(entry.Name()) == ".json" </span><span class="cov8" title="1">{
|
||||
// Process JSON files
|
||||
compiledSchema, err := compiler.Compile(path)
|
||||
if err != nil </span><span class="cov8" title="1">{
|
||||
return fmt.Errorf("failed to compile JSON schema from file %s: %v", entry.Name(), err)
|
||||
}</span>
|
||||
<span class="cov8" title="1">if compiledSchema == nil </span><span class="cov0" title="0">{
|
||||
return fmt.Errorf("compiled schema is nil for file %s", entry.Name())
|
||||
}</span>
|
||||
|
||||
// Use relative path from schemaDir to avoid absolute paths and make schema keys domain/version specific.
|
||||
<span class="cov8" title="1">relativePath, err := filepath.Rel(schemaDir, path)
|
||||
if err != nil </span><span class="cov0" title="0">{
|
||||
return fmt.Errorf("failed to get relative path for file %s: %v", entry.Name(), err)
|
||||
}</span>
|
||||
// Ensure relativePath is not empty
|
||||
<span class="cov8" title="1">if relativePath == "" </span><span class="cov0" title="0">{
|
||||
return fmt.Errorf("relative path is empty for file: %s", path)
|
||||
}</span>
|
||||
// Split the relative path to get domain, version, and schema.
|
||||
<span class="cov8" title="1">parts := strings.Split(relativePath, string(os.PathSeparator))
|
||||
|
||||
// Ensure that the file path has at least 3 parts: domain, version, and schema file.
|
||||
if len(parts) < 3 </span><span class="cov0" title="0">{
|
||||
return fmt.Errorf("invalid schema file structure, expected domain/version/schema.json but got: %s", relativePath)
|
||||
}</span>
|
||||
|
||||
// Extract domain, version, and schema filename from the parts.
|
||||
// Validate that the extracted parts are non-empty
|
||||
<span class="cov8" title="1">domain := strings.TrimSpace(parts[0])
|
||||
version := strings.TrimSpace(parts[1])
|
||||
schemaFileName := strings.TrimSpace(parts[2])
|
||||
|
||||
if domain == "" || version == "" || schemaFileName == "" </span><span class="cov0" title="0">{
|
||||
return fmt.Errorf("invalid schema file structure, one or more components are empty. Relative path: %s", relativePath)
|
||||
}</span>
|
||||
|
||||
// Construct a unique key combining domain, version, and schema name (e.g., ondc_trv10/v2.0.0/schema.json).
|
||||
<span class="cov8" title="1">uniqueKey := fmt.Sprintf("%s/%s/%s", domain, version, schemaFileName)
|
||||
// Store the compiled schema in the SchemaCache using the unique key.
|
||||
vp.SchemaCache[uniqueKey] = compiledSchema
|
||||
// Store the corresponding validator in the validatorCache using the same unique key.
|
||||
validatorCache[uniqueKey] = &TekuriValidator{schema: compiledSchema}</span>
|
||||
}
|
||||
}
|
||||
<span class="cov8" title="1">return nil</span>
|
||||
}
|
||||
|
||||
// Start processing from the root schema directory
|
||||
<span class="cov8" title="1">if err := processDir(schemaDir); err != nil </span><span class="cov8" title="1">{
|
||||
return nil, fmt.Errorf("failed to read schema directory: %v", err)
|
||||
}</span>
|
||||
|
||||
<span class="cov8" title="1">return validatorCache, nil</span>
|
||||
}
|
||||
|
||||
var _ definitions.ValidatorProvider = (*TekuriValidatorProvider)(nil)
|
||||
|
||||
var providerInstance = &TekuriValidatorProvider{}
|
||||
|
||||
// GetProvider returns the ValidatorProvider instance.
|
||||
func GetProvider() definitions.ValidatorProvider <span class="cov8" title="1">{
|
||||
return providerInstance
|
||||
}</span>
|
||||
</pre>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
<script>
|
||||
(function() {
|
||||
var files = document.getElementById('files');
|
||||
var visible;
|
||||
files.addEventListener('change', onChange, false);
|
||||
function select(part) {
|
||||
if (visible)
|
||||
visible.style.display = 'none';
|
||||
visible = document.getElementById(part);
|
||||
if (!visible)
|
||||
return;
|
||||
files.value = part;
|
||||
visible.style.display = 'block';
|
||||
location.hash = part;
|
||||
}
|
||||
function onChange() {
|
||||
select(files.value);
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
if (location.hash != "") {
|
||||
select(location.hash.substr(1));
|
||||
}
|
||||
if (!visible) {
|
||||
select("file0");
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</html>
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"beckn-onix/plugins"
|
||||
"beckn-onix/plugins/definitions"
|
||||
|
||||
"github.com/santhosh-tekuri/jsonschema/v6"
|
||||
)
|
||||
@@ -41,69 +41,99 @@ func (v *TekuriValidator) Validate(ctx context.Context, data []byte) error {
|
||||
// Initialize initializes the validator provider by compiling all the JSON schema files
|
||||
// from the specified directory and storing them in a cache. It returns a map of validators
|
||||
// indexed by their schema filenames.
|
||||
func (vp *TekuriValidatorProvider) Initialize(schemaDir string) (map[string]plugins.Validator, error) {
|
||||
// Initialize the SchemaCache map to store the compiled schemas using a unique key (domain/version/schema).
|
||||
vp.SchemaCache = make(map[string]*jsonschema.Schema)
|
||||
func (vp *TekuriValidatorProvider) Initialize(schemaDir string) (map[string]definitions.Validator, error) {
|
||||
// Initialize SchemaCache if it's nil
|
||||
if vp.SchemaCache == nil {
|
||||
vp.SchemaCache = make(map[string]*jsonschema.Schema)
|
||||
}
|
||||
// Check if the directory exists and is accessible
|
||||
info, err := os.Stat(schemaDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("schema directory does not exist: %s", schemaDir)
|
||||
}
|
||||
return nil, fmt.Errorf("failed to access schema directory: %v", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return nil, fmt.Errorf("provided schema path is not a directory: %s", schemaDir)
|
||||
}
|
||||
|
||||
// Initialize the validatorCache map to store the Validator instances associated with each schema.
|
||||
validatorCache := make(map[string]plugins.Validator)
|
||||
validatorCache := make(map[string]definitions.Validator)
|
||||
compiler := jsonschema.NewCompiler()
|
||||
|
||||
// Walk through the schema directory and process each file.
|
||||
err := filepath.Walk(schemaDir, func(path string, info os.FileInfo, err error) error {
|
||||
// Helper function to process directories recursively
|
||||
var processDir func(dir string) error
|
||||
processDir = func(dir string) error {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("failed to read directory: %v", err)
|
||||
}
|
||||
|
||||
// Only process files (ignore directories) and ensure the file has a ".json" extension.
|
||||
if !info.IsDir() && filepath.Ext(info.Name()) == ".json" {
|
||||
compiledSchema, err := compiler.Compile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to compile JSON schema from file %s: %v", info.Name(), err)
|
||||
for _, entry := range entries {
|
||||
path := filepath.Join(dir, entry.Name())
|
||||
if entry.IsDir() {
|
||||
// Recursively process subdirectories
|
||||
if err := processDir(path); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if filepath.Ext(entry.Name()) == ".json" {
|
||||
// Process JSON files
|
||||
compiledSchema, err := compiler.Compile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to compile JSON schema from file %s: %v", entry.Name(), err)
|
||||
}
|
||||
if compiledSchema == nil {
|
||||
return fmt.Errorf("compiled schema is nil for file %s", entry.Name())
|
||||
}
|
||||
|
||||
// Use relative path from schemaDir to avoid absolute paths and make schema keys domain/version specific.
|
||||
relativePath, err := filepath.Rel(schemaDir, path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get relative path for file %s: %v", entry.Name(), err)
|
||||
}
|
||||
// Split the relative path to get domain, version, and schema.
|
||||
parts := strings.Split(relativePath, string(os.PathSeparator))
|
||||
|
||||
// Ensure that the file path has at least 3 parts: domain, version, and schema file.
|
||||
if len(parts) < 3 {
|
||||
return fmt.Errorf("invalid schema file structure, expected domain/version/schema.json but got: %s", relativePath)
|
||||
}
|
||||
|
||||
// Extract domain, version, and schema filename from the parts.
|
||||
// Validate that the extracted parts are non-empty
|
||||
domain := strings.TrimSpace(parts[0])
|
||||
version := strings.TrimSpace(parts[1])
|
||||
schemaFileName := strings.TrimSpace(parts[2])
|
||||
|
||||
if domain == "" || version == "" || schemaFileName == "" {
|
||||
return fmt.Errorf("invalid schema file structure, one or more components are empty. Relative path: %s", relativePath)
|
||||
}
|
||||
|
||||
// Construct a unique key combining domain, version, and schema name (e.g., ondc_trv10/v2.0.0/schema.json).
|
||||
uniqueKey := fmt.Sprintf("%s/%s/%s", domain, version, schemaFileName)
|
||||
// Store the compiled schema in the SchemaCache using the unique key.
|
||||
vp.SchemaCache[uniqueKey] = compiledSchema
|
||||
// Store the corresponding validator in the validatorCache using the same unique key.
|
||||
validatorCache[uniqueKey] = &TekuriValidator{schema: compiledSchema}
|
||||
}
|
||||
if compiledSchema == nil {
|
||||
return fmt.Errorf("compiled schema is nil for file %s", info.Name())
|
||||
}
|
||||
|
||||
// Use relative path from schemaDir to avoid absolute paths and make schema keys domain/version specific.
|
||||
relativePath, err := filepath.Rel(schemaDir, path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get relative path for file %s: %v", info.Name(), err)
|
||||
}
|
||||
// Split the relative path to get domain, version, and schema.
|
||||
parts := strings.Split(relativePath, string(os.PathSeparator))
|
||||
|
||||
// Ensure that the file path has at least 3 parts: domain, version, and schema file.
|
||||
if len(parts) < 3 {
|
||||
return fmt.Errorf("invalid schema file structure, expected domain/version/schema.json but got: %s", relativePath)
|
||||
}
|
||||
|
||||
// Extract domain, version, and schema filename from the parts.
|
||||
domain := parts[0]
|
||||
version := parts[1]
|
||||
schemaFileName := parts[2]
|
||||
|
||||
// Construct a unique key combining domain, version, and schema name (e.g., ondc_trv10/v2.0.0/schema.json).
|
||||
uniqueKey := fmt.Sprintf("%s/%s/%s", domain, version, schemaFileName)
|
||||
// Store the compiled schema in the SchemaCache using the unique key.
|
||||
vp.SchemaCache[uniqueKey] = compiledSchema
|
||||
// Store the corresponding validator in the validatorCache using the same unique key.
|
||||
validatorCache[uniqueKey] = &TekuriValidator{schema: compiledSchema}
|
||||
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
}
|
||||
|
||||
// Start processing from the root schema directory
|
||||
if err := processDir(schemaDir); err != nil {
|
||||
return nil, fmt.Errorf("failed to read schema directory: %v", err)
|
||||
}
|
||||
|
||||
return validatorCache, nil
|
||||
}
|
||||
|
||||
var _ plugins.ValidatorProvider = (*TekuriValidatorProvider)(nil)
|
||||
var _ definitions.ValidatorProvider = (*TekuriValidatorProvider)(nil)
|
||||
|
||||
var providerInstance = &TekuriValidatorProvider{}
|
||||
|
||||
// GetProvider returns the ValidatorProvider instance.
|
||||
func GetProvider() plugins.ValidatorProvider {
|
||||
func GetProvider() definitions.ValidatorProvider {
|
||||
return providerInstance
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -15,10 +17,9 @@ type Payload struct {
|
||||
}
|
||||
|
||||
type Context struct{}
|
||||
|
||||
type Message struct{}
|
||||
|
||||
func TestInitializeValidDirectory(t *testing.T) {
|
||||
func TestValidDirectory(t *testing.T) {
|
||||
provider := &TekuriValidatorProvider{}
|
||||
schemaDir := "../testData/schema_valid/"
|
||||
_, err := provider.Initialize(schemaDir)
|
||||
@@ -27,46 +28,7 @@ func TestInitializeValidDirectory(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeInValidDirectory(t *testing.T) {
|
||||
provider := &TekuriValidatorProvider{}
|
||||
schemaDir := "../testData/schema/ondc_trv10/"
|
||||
_, err := provider.Initialize(schemaDir)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read schema directory: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidCompileFile(t *testing.T) {
|
||||
schemaDir := "../testData/invalid_compile_schema/"
|
||||
if _, err := os.Stat(schemaDir); os.IsNotExist(err) {
|
||||
t.Fatalf("Schema directory does not exist: %v", schemaDir)
|
||||
}
|
||||
provider := &TekuriValidatorProvider{}
|
||||
compiledSchema, err := provider.Initialize(schemaDir)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to compile JSON schema : %v", err)
|
||||
}
|
||||
if compiledSchema == nil {
|
||||
t.Fatalf("compiled schema is nil : ")
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidCompileSchema(t *testing.T) {
|
||||
schemaDir := "../testData/invalid_schemas/"
|
||||
if _, err := os.Stat(schemaDir); os.IsNotExist(err) {
|
||||
t.Fatalf("Schema directory does not exist: %v", schemaDir)
|
||||
}
|
||||
provider := &TekuriValidatorProvider{}
|
||||
compiledSchema, _ := provider.Initialize(schemaDir)
|
||||
fmt.Println(compiledSchema)
|
||||
if compiledSchema == nil {
|
||||
t.Fatalf("compiled schema is nil : ")
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateData(t *testing.T) {
|
||||
func TestValidPayload(t *testing.T) {
|
||||
schemaDir := "../testData/schema_valid/"
|
||||
if _, err := os.Stat(schemaDir); os.IsNotExist(err) {
|
||||
t.Fatalf("Schema directory does not exist: %v", schemaDir)
|
||||
@@ -88,7 +50,7 @@ func TestValidateData(t *testing.T) {
|
||||
t.Fatalf("No validators found in the map")
|
||||
}
|
||||
|
||||
payloadFilePath := "../testData/cancel.json"
|
||||
payloadFilePath := "../testData/payloads/search.json"
|
||||
payloadData, err := os.ReadFile(payloadFilePath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read payload data: %v", err)
|
||||
@@ -106,13 +68,127 @@ func TestValidateData(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInValidateData(t *testing.T) {
|
||||
func TestInValidDirectory(t *testing.T) {
|
||||
provider := &TekuriValidatorProvider{}
|
||||
schemaDir := "../testData/schema/ondc_trv10/"
|
||||
_, err := provider.Initialize(schemaDir)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read schema directory: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidCompileFile(t *testing.T) {
|
||||
schemaDir := "../testData/invalid_compile_schema/"
|
||||
// if _, err := os.Stat(schemaDir); os.IsNotExist(err) {
|
||||
// t.Fatalf("Schema directory does not exist: %v", schemaDir)
|
||||
// }
|
||||
provider := &TekuriValidatorProvider{}
|
||||
_, err := provider.Initialize(schemaDir)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to compile JSON schema : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidCompileSchema(t *testing.T) {
|
||||
schemaDir := "../testData/invalid_schemas/"
|
||||
if _, err := os.Stat(schemaDir); os.IsNotExist(err) {
|
||||
t.Fatalf("Schema directory does not exist: %v", schemaDir)
|
||||
}
|
||||
provider := &TekuriValidatorProvider{}
|
||||
compiledSchema, _ := provider.Initialize(schemaDir)
|
||||
fmt.Println(compiledSchema)
|
||||
if compiledSchema == nil {
|
||||
t.Fatalf("compiled schema is nil : ")
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestPayloadWithExtraFields(t *testing.T) {
|
||||
schemaDir := "../testData/schema_valid/"
|
||||
if _, err := os.Stat(schemaDir); os.IsNotExist(err) {
|
||||
t.Fatalf("Schema directory does not exist: %v", schemaDir)
|
||||
}
|
||||
provider := &TekuriValidatorProvider{}
|
||||
validators, err := provider.Initialize(schemaDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize schema provider: %v", err)
|
||||
}
|
||||
var validator *TekuriValidator
|
||||
for _, v := range validators {
|
||||
var ok bool
|
||||
validator, ok = v.(*TekuriValidator)
|
||||
if ok {
|
||||
break
|
||||
}
|
||||
}
|
||||
if validator == nil {
|
||||
t.Fatalf("No validators found in the map")
|
||||
}
|
||||
payloadFilePath := "../testData/payloads/search_extraField.json"
|
||||
payloadData, err := os.ReadFile(payloadFilePath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read payload data: %v", err)
|
||||
}
|
||||
var payload Payload
|
||||
err = json.Unmarshal(payloadData, &payload)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to unmarshal payload data: %v", err)
|
||||
}
|
||||
err = validator.Validate(context.Background(), payloadData)
|
||||
if err != nil {
|
||||
t.Errorf("Validation failed due to extra fields: %v", err)
|
||||
} else {
|
||||
fmt.Println("Validation succeeded.")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestPayloadWithMissingFields(t *testing.T) {
|
||||
schemaDir := "../testData/schema_valid/"
|
||||
if _, err := os.Stat(schemaDir); os.IsNotExist(err) {
|
||||
t.Fatalf("Schema directory does not exist: %v", schemaDir)
|
||||
}
|
||||
provider := &TekuriValidatorProvider{}
|
||||
validators, err := provider.Initialize(schemaDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize schema provider: %v", err)
|
||||
}
|
||||
var validator *TekuriValidator
|
||||
for _, v := range validators {
|
||||
var ok bool
|
||||
validator, ok = v.(*TekuriValidator)
|
||||
if ok {
|
||||
break
|
||||
}
|
||||
}
|
||||
if validator == nil {
|
||||
t.Fatalf("No validators found in the map")
|
||||
}
|
||||
payloadFilePath := "../testData/payloads/search_missingField.json"
|
||||
payloadData, err := os.ReadFile(payloadFilePath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read payload data: %v", err)
|
||||
}
|
||||
var payload Payload
|
||||
err = json.Unmarshal(payloadData, &payload)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to unmarshal payload data: %v", err)
|
||||
}
|
||||
err = validator.Validate(context.Background(), payloadData)
|
||||
if err != nil {
|
||||
t.Errorf("Validation failed with missing fields: %v", err)
|
||||
} else {
|
||||
fmt.Println("Validation succeeded.")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestInValidPayload(t *testing.T) {
|
||||
schemaDir := "../testData/schema_valid/"
|
||||
|
||||
if _, err := os.Stat(schemaDir); os.IsNotExist(err) {
|
||||
t.Fatalf("Schema directory does not exist: %v", schemaDir)
|
||||
}
|
||||
|
||||
provider := &TekuriValidatorProvider{}
|
||||
validators, err := provider.Initialize(schemaDir)
|
||||
if err != nil {
|
||||
@@ -132,7 +208,7 @@ func TestInValidateData(t *testing.T) {
|
||||
invalidPayloadData := []byte(`"invalid": "data"}`)
|
||||
err = validator.Validate(context.Background(), invalidPayloadData)
|
||||
if err != nil {
|
||||
t.Errorf("Validation failed: %v", err)
|
||||
t.Fatalf("Validation failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,3 +252,52 @@ func TestGetProvider(t *testing.T) {
|
||||
t.Logf("GetProvider returned the expected providerInstance")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitialize_SchemaPathNotDirectory(t *testing.T) {
|
||||
vp := &TekuriValidatorProvider{}
|
||||
filePath := "../testdata/directory.json"
|
||||
|
||||
_, err := vp.Initialize(filePath)
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), "provided schema path is not a directory") {
|
||||
t.Errorf("Expected error about non-directory schema path, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitialize_InvalidSchemaFileStructure(t *testing.T) {
|
||||
schemaDir := "../testData/invalid_structure"
|
||||
provider := &TekuriValidatorProvider{}
|
||||
|
||||
_, err := provider.Initialize(schemaDir)
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid schema file structure") {
|
||||
t.Fatalf("Expected error for invalid schema file structure, got: %v", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestInitialize_FailedToGetRelativePath(t *testing.T) {
|
||||
schemaDir := "../testData/valid_schemas"
|
||||
provider := &TekuriValidatorProvider{}
|
||||
|
||||
// Use an absolute path for schemaDir and a relative path for the file to simulate the error
|
||||
absSchemaDir, err := filepath.Abs(schemaDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get absolute path for schema directory: %v", err)
|
||||
}
|
||||
|
||||
// Temporarily change the working directory to simulate different volumes
|
||||
originalWd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get current working directory: %v", err)
|
||||
}
|
||||
defer os.Chdir(originalWd) // Restore the original working directory after the test
|
||||
|
||||
// Change to a different directory
|
||||
os.Chdir("/tmp")
|
||||
|
||||
_, err = provider.Initialize(absSchemaDir)
|
||||
if err == nil || !strings.Contains(err.Error(), "failed to get relative path for file") {
|
||||
t.Fatalf("Expected error for failing to get relative path, got: %v", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user