Enhance NormalizeISBN to validate and convert ISBNs: - Validate length (10 or 13 digits), return error if invalid - Convert ISBN-10 to ISBN-13 by prefixing '978' and recalculating checksum - Add NormalizeISBNSafe for backward compatibility in scanners This ensures all ISBNs stored in database are valid ISBN-13 format.
119 lines
2.3 KiB
Go
119 lines
2.3 KiB
Go
package utils
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestNormalizeISBN_Validation(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected string
|
|
expectError bool
|
|
}{
|
|
{
|
|
name: "valid ISBN-13",
|
|
input: "978-0-306-40615-7",
|
|
expected: "9780306406157",
|
|
expectError: false,
|
|
},
|
|
{
|
|
name: "valid ISBN-10 converts to ISBN-13",
|
|
input: "0-306-40615-2",
|
|
expected: "9780306406157",
|
|
expectError: false,
|
|
},
|
|
{
|
|
name: "ISBN-10 with X converts to ISBN-13",
|
|
input: "0-596-00965-X",
|
|
expected: "9780596009656",
|
|
expectError: false,
|
|
},
|
|
{
|
|
name: "empty string",
|
|
input: "",
|
|
expected: "",
|
|
expectError: false,
|
|
},
|
|
{
|
|
name: "11 digits - invalid",
|
|
input: "97801234567",
|
|
expected: "",
|
|
expectError: true,
|
|
},
|
|
{
|
|
name: "12 digits - invalid",
|
|
input: "978012345678",
|
|
expected: "",
|
|
expectError: true,
|
|
},
|
|
{
|
|
name: "14 digits - invalid",
|
|
input: "97801234567890",
|
|
expected: "",
|
|
expectError: true,
|
|
},
|
|
{
|
|
name: "only hyphens",
|
|
input: "---",
|
|
expected: "",
|
|
expectError: true,
|
|
},
|
|
{
|
|
name: "only text",
|
|
input: "not-an-isbn",
|
|
expected: "",
|
|
expectError: true,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := NormalizeISBN(tt.input)
|
|
|
|
if tt.expectError {
|
|
require.Error(t, err)
|
|
assert.Equal(t, "", result)
|
|
} else {
|
|
require.NoError(t, err)
|
|
assert.Equal(t, tt.expected, result)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestConvertISBN10To13(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
isbn10 string
|
|
expected string
|
|
}{
|
|
{
|
|
name: "ISBN-10 0-306-40615-2",
|
|
isbn10: "0306406152",
|
|
expected: "9780306406157",
|
|
},
|
|
{
|
|
name: "ISBN-10 0-596-00965-X (X checksum)",
|
|
isbn10: "059600965X",
|
|
expected: "9780596009656",
|
|
},
|
|
{
|
|
name: "ISBN-10 0-8044-2957-X",
|
|
isbn10: "080442957X",
|
|
expected: "9780804429573",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := convertISBN10To13(tt.isbn10)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, tt.expected, result)
|
|
})
|
|
}
|
|
}
|