llama_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package llama
  2. import (
  3. "strings"
  4. "testing"
  5. "github.com/google/go-cmp/cmp"
  6. )
  7. func TestJsonSchema(t *testing.T) {
  8. testCases := []struct {
  9. name string
  10. schema JsonSchema
  11. expected string
  12. }{
  13. {
  14. name: "empty schema",
  15. schema: JsonSchema{
  16. Type: "object",
  17. },
  18. expected: `array ::= "[" space ( value ("," space value)* )? "]" space
  19. boolean ::= ("true" | "false") space
  20. char ::= [^"\\\x7F\x00-\x1F] | [\\] (["\\bfnrt] | "u" [0-9a-fA-F]{4})
  21. decimal-part ::= [0-9]{1,16}
  22. integral-part ::= [0] | [1-9] [0-9]{0,15}
  23. null ::= "null" space
  24. number ::= ("-"? integral-part) ("." decimal-part)? ([eE] [-+]? integral-part)? space
  25. object ::= "{" space ( string ":" space value ("," space string ":" space value)* )? "}" space
  26. root ::= object
  27. space ::= | " " | "\n" [ \t]{0,20}
  28. string ::= "\"" char* "\"" space
  29. value ::= object | array | string | number | boolean | null`,
  30. },
  31. {
  32. name: "invalid schema with circular reference",
  33. schema: JsonSchema{
  34. Type: "object",
  35. Properties: map[string]any{
  36. "self": map[string]any{
  37. "$ref": "#", // Self reference
  38. },
  39. },
  40. },
  41. expected: "", // Should return empty string for invalid schema
  42. },
  43. {
  44. name: "schema with invalid type",
  45. schema: JsonSchema{
  46. Type: "invalid_type", // Invalid type
  47. Properties: map[string]any{
  48. "foo": map[string]any{
  49. "type": "string",
  50. },
  51. },
  52. },
  53. expected: "", // Should return empty string for invalid schema
  54. },
  55. }
  56. for _, tc := range testCases {
  57. t.Run(tc.name, func(t *testing.T) {
  58. result := tc.schema.AsGrammar()
  59. if !strings.EqualFold(strings.TrimSpace(result), strings.TrimSpace(tc.expected)) {
  60. if diff := cmp.Diff(tc.expected, result); diff != "" {
  61. t.Fatalf("grammar mismatch (-want +got):\n%s", diff)
  62. }
  63. }
  64. })
  65. }
  66. }