| 1 |
// |
| 2 |
// Copyright 2006-2019 WebPKI.org (http://webpki.org). |
| 3 |
// |
| 4 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
// you may not use this file except in compliance with the License. |
| 6 |
// You may obtain a copy of the License at |
| 7 |
// |
| 8 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
// |
| 10 |
// Unless required by applicable law or agreed to in writing, software |
| 11 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
// See the License for the specific language governing permissions and |
| 14 |
// limitations under the License. |
| 15 |
// |
| 16 |
|
| 17 |
// This program verifies the JSON canonicalizer using a test suite |
| 18 |
// containing sample data and expected output |
| 19 |
|
| 20 |
package main |
| 21 |
|
| 22 |
import ( |
| 23 |
"fmt" |
| 24 |
"io/ioutil" |
| 25 |
"runtime" |
| 26 |
"path/filepath" |
| 27 |
"bytes" |
| 28 |
"webpki.org/jsoncanonicalizer" |
| 29 |
) |
| 30 |
|
| 31 |
func check(e error) { |
| 32 |
if e != nil { |
| 33 |
panic(e) |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
var testdata string |
| 38 |
|
| 39 |
var failures = 0 |
| 40 |
|
| 41 |
func read(fileName string, directory string) []byte { |
| 42 |
data, err := ioutil.ReadFile(filepath.Join(filepath.Join(testdata, directory), fileName)) |
| 43 |
check(err) |
| 44 |
return data |
| 45 |
} |
| 46 |
|
| 47 |
func verify(fileName string) { |
| 48 |
actual, err := jsoncanonicalizer.Transform(read(fileName, "input")) |
| 49 |
check(err) |
| 50 |
recycled, err2 := jsoncanonicalizer.Transform(actual) |
| 51 |
check(err2) |
| 52 |
expected := read(fileName, "output") |
| 53 |
var utf8InHex = "\nFile: " + fileName |
| 54 |
var byteCount = 0 |
| 55 |
var next = false |
| 56 |
for _, b := range actual { |
| 57 |
if byteCount % 32 == 0 { |
| 58 |
utf8InHex = utf8InHex + "\n" |
| 59 |
next = false |
| 60 |
} |
| 61 |
byteCount++ |
| 62 |
if next { |
| 63 |
utf8InHex = utf8InHex + " " |
| 64 |
} |
| 65 |
next = true |
| 66 |
utf8InHex = utf8InHex + fmt.Sprintf("%02x", b) |
| 67 |
} |
| 68 |
fmt.Println(utf8InHex + "\n") |
| 69 |
if !bytes.Equal(actual, expected) || !bytes.Equal(actual, recycled) { |
| 70 |
failures++ |
| 71 |
fmt.Println("THE TEST ABOVE FAILED!"); |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
func main() { |
| 76 |
_, executable, _, _ := runtime.Caller(0) |
| 77 |
testdata = filepath.Join(filepath.Dir(filepath.Dir(filepath.Dir(executable))), "testdata") |
| 78 |
fmt.Println(testdata) |
| 79 |
files, err := ioutil.ReadDir(filepath.Join(testdata, "input")) |
| 80 |
check(err) |
| 81 |
for _, file := range files { |
| 82 |
verify(file.Name()) |
| 83 |
} |
| 84 |
if failures == 0 { |
| 85 |
fmt.Println("All tests succeeded!\n") |
| 86 |
} else { |
| 87 |
fmt.Printf("\n****** ERRORS: %d *******\n", failures) |
| 88 |
} |
| 89 |
} |