package utils

import (
	"testing"
)

var (
	tests = []struct {
		caseName string
		inCert   []byte
		inRootCA []byte
		out      bool
	}{
		{"cert self signed", selfSignedCert, selfSignedCA, true},
		{"cert signed by let's encript", letEncriptSignedCert, letEncriptSignedCA, true},
		{"miss match cert and ca", selfSignedCert, letEncriptSignedCA, false},
	}
)

func TestIsSignedBy(t *testing.T) {

	for _, tt := range tests {
		certs, err := loadCertsFromPEM(tt.inCert)
		if err != nil {
			t.Error(err)
			continue
		}

		if len(certs) == 0 {
			t.Errorf("test %s failed, load cert failed", tt.caseName)
			continue
		}

		cas, err := loadCertsFromPEM(tt.inRootCA)
		if err != nil {
			t.Error(err)
			continue
		}

		if len(cas) == 0 {
			t.Errorf("test %s failed, load rootCA failed", tt.caseName)
			continue
		}

		cert := certs[0]
		ca := cas[0]
		actual := isSignedBy(cert, ca)
		if actual != tt.out {
			t.Errorf("test %s failed, expect %v, actual %v", tt.caseName, tt.out, actual)
		}
	}
}

var (
	selfSignedCert = []byte(`-----BEGIN CERTIFICATE-----
MIIDPDCCAiQCCQCbWizd273aVzANBgkqhkiG9w0BAQsFADBgMQswCQYDVQQGEwJV
SzEPMA0GA1UEBwwGTG9uZG9uMQ0wCwYDVQQKDAROb25lMQ0wCwYDVQQLDAROb25l
MSIwIAYDVQQDDBltaWNoZWxpYS5yYW5jaGVyLXRlc3QuY29tMB4XDTE5MDIwMTE2
MjM1NloXDTIwMDYxNTE2MjM1NlowYDELMAkGA1UEBhMCVUsxDzANBgNVBAcMBkxv
bmRvbjENMAsGA1UECgwETm9uZTENMAsGA1UECwwETm9uZTEiMCAGA1UEAwwZbWlj
aGVsaWEucmFuY2hlci10ZXN0LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBANBQq82F9AGYvB1tdx5uR9uBSnOhyDy+XFtJdW7B6hyrYTffpGPFfT4n
6GPyFTgC6k5ueiLSfk+2kDRWGczNva/FMh0ZywUmDHpWQp2M7+6/PJzFpgafXJ0T
pLMLSRv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