git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/barcode/ean/encoder_test.go (about)

     1  package ean
     2  
     3  import (
     4  	"image/color"
     5  	"testing"
     6  )
     7  
     8  func testHelper(t *testing.T, testCode, testResult, kind string, checkMetadata bool) {
     9  	code, err := Encode(testCode)
    10  	if err != nil {
    11  		t.Error(err)
    12  	}
    13  	if checkMetadata && (code.Metadata().Dimensions != 1 || code.Content() != testCode || code.Metadata().CodeKind != kind) {
    14  		t.Error("Metadata missmatch")
    15  	}
    16  	if len(testResult) != code.Bounds().Max.X {
    17  		t.Fail()
    18  	}
    19  	for i, r := range testResult {
    20  		if (code.At(i, 0) == color.Black) != (r == '1') {
    21  			t.Fail()
    22  		}
    23  	}
    24  }
    25  
    26  func Test_EncodeEAN(t *testing.T) {
    27  	testHelper(t, "5901234123457", "10100010110100111011001100100110111101001110101010110011011011001000010101110010011101000100101", "EAN 13", true)
    28  	testHelper(t, "55123457", "1010110001011000100110010010011010101000010101110010011101000100101", "EAN 8", true)
    29  	testHelper(t, "5512345", "1010110001011000100110010010011010101000010101110010011101000100101", "EAN 8", false)
    30  	_, err := Encode("55123458") //<-- Invalid checksum
    31  	if err == nil {
    32  		t.Error("Invalid checksum not detected")
    33  	}
    34  	_, err = Encode("invalid")
    35  	if err == nil {
    36  		t.Error("\"invalid\" should not be encodable")
    37  	}
    38  	_, err = Encode("invalid")
    39  	if err == nil {
    40  		t.Error("\"invalid\" should not be encodable")
    41  	}
    42  	bits := encodeEAN13("invalid error")
    43  	if bits != nil {
    44  		t.Error("\"invalid error\" should not be encodable")
    45  	}
    46  }