github.com/tompreston/snapd@v0.0.0-20210817193607-954edfcb9611/testutil/jsonchecker.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2021 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package testutil
    21  
    22  import (
    23  	"encoding/json"
    24  	"fmt"
    25  
    26  	"gopkg.in/check.v1"
    27  )
    28  
    29  type jsonEqualChecker struct {
    30  	*check.CheckerInfo
    31  }
    32  
    33  // JsonEquals compares the obtained and expected values after having serialized
    34  // them to JSON and deserialized to a generic interface{} type. This avoids
    35  // trouble comparing types with unexported fields that otherwise would be
    36  // problematic to set in external packages.
    37  var JsonEquals check.Checker = &jsonEqualChecker{
    38  	&check.CheckerInfo{Name: "JsonEqual", Params: []string{"obtained", "expected"}},
    39  }
    40  
    41  func (c *jsonEqualChecker) Check(params []interface{}, names []string) (result bool, error string) {
    42  	toComparableMap := func(what interface{}) interface{} {
    43  		b, err := json.Marshal(what)
    44  		if err != nil {
    45  			panic("cannot marshal")
    46  		}
    47  		var back interface{}
    48  		if err := json.Unmarshal(b, &back); err != nil {
    49  			panic(fmt.Sprintf("cannot unmarshal from: %s", string(b)))
    50  		}
    51  		return back
    52  	}
    53  
    54  	obtained := toComparableMap(params[0])
    55  	ref := toComparableMap(params[1])
    56  
    57  	return check.DeepEquals.Check([]interface{}{obtained, ref}, names)
    58  }