/*
Copyright 2020 The Knative Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package depcheck_test demonstrates the usage of depcheck.
// Tests should be put into the special `_test` package to avoid
// polluting the dependencies of the package they are testing.
package depcheck_test

import (
	"strings"
	"testing"

	"github.com/depcheck-test/depcheck-test/depcheck"
)

const thisPackage = "github.com/depcheck-test/depcheck-test/depcheck"
const golangXPackages = "golang.org/x/tools/go/packages"

// TestExample doesn't follow the Go Example style because it isn't well
// suited for libraries needing *testing.T
func TestExample(t *testing.T) {

	// Check that this package doesn't depend on a known heavy package.
	depcheck.AssertNoDependency(t, map[string][]string{
		"github.com/depcheck-test/depcheck-test/depcheck": {"k8s.io/apimachinery/pkg/api/apitesting/fuzzer"},
	})

	// Sample failure case, this package depends on golang.org/x/tools/go/packages.
	if err := depcheck.CheckNoDependency("github.com/depcheck-test/depcheck-test/depcheck", []string{"golang.org/x/tools/go/packages"}); err == nil {
		t.Error("CheckNoDependency() = nil, wanted error")
	} else if !strings.Contains(err.Error(), "depends on banned dependency") {
		t.Errorf("CheckNoDependency() = %v, expected to contain: %q", err, "depends on banned dependency")
	} else {
		t.Log("CheckNoDependency() =", err)
	}

	// For small packages, it can make the most sense to curate
	// the external dependencies very carefully.
	depcheck.AssertOnlyDependencies(t, map[string][]string{
		"github.com/depcheck-test/depcheck-test/testdata": {"fmt"},
	})

	// Sample failure case, doesn't include transitive dependencies!
	if err := depcheck.CheckOnlyDependencies(thisPackage, map[string]struct{}{
		"fmt":                            {},
		"sort":                           {},
		"strings":                        {},
		"testing":                        {},
		"golang.org/x/tools/go/packages": {},
	}); err == nil {
		t.Error("CheckOnlyDependencies() = nil, wanted error")
	} else if !strings.Contains(err.Error(), "golang.org/x/tools/go/gcexportdata") {
		t.Errorf("CheckOnlyDependencies() = %v, expected to contain: %v", err, "golang.org/x/tools/go/gcexportdata")
	}
}
