79 lines
2.2 KiB
Go
79 lines
2.2 KiB
Go
package lang
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestGenerateRustStyleEnumAndExhaustiveMatch(t *testing.T) {
|
|
prog, err := Parse(`
|
|
package demo
|
|
enum PaymentResult { Accepted(String), Rejected(String), Pending }
|
|
fun describe(result: PaymentResult): String {
|
|
var description = ""
|
|
match (result) {
|
|
PaymentResult::Accepted(id) -> { description = id }
|
|
PaymentResult::Rejected(reason) -> { description = reason }
|
|
PaymentResult::Pending -> { description = "pending" }
|
|
}
|
|
return description
|
|
}
|
|
fun main() { println(describe(PaymentResult::Accepted("p1"))) }
|
|
`)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
out, err := GenerateGo(prog)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, want := range []string{"type PaymentResult interface", "type PaymentResultAccepted struct", "&PaymentResultAccepted{Value0: \"p1\"}", "case *PaymentResultRejected:", "reason := gotlinMatch1.Value0"} {
|
|
if !strings.Contains(string(out), want) {
|
|
t.Fatalf("missing %q:\n%s", want, out)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRejectNonExhaustiveEnumMatch(t *testing.T) {
|
|
prog, err := Parse(`package demo
|
|
enum Result { Ok, Error(String) }
|
|
fun use(result: Result) { match (result) { Result::Ok -> { println("ok") } } }`)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, err = GenerateGo(prog)
|
|
if err == nil || !strings.Contains(err.Error(), "missing Error") {
|
|
t.Fatalf("expected exhaustive-match error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestRejectWrongVariantPayloadCount(t *testing.T) {
|
|
prog, err := Parse(`package demo
|
|
enum Result { Ok(String) }
|
|
fun main() { val result = Result::Ok() }`)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, err = GenerateGo(prog)
|
|
if err == nil || !strings.Contains(err.Error(), "expects 1 values") {
|
|
t.Fatalf("expected payload error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestPayloadlessEnumUsesExactVariantStrings(t *testing.T) {
|
|
prog, err := Parse(`package demo
|
|
enum Status { PendingReservation, Initiated }
|
|
fun main() { println(Status::PendingReservation) }`)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
out, err := GenerateGo(prog)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, want := range []string{`type Status string`, `StatusPendingReservation`, `"PendingReservation"`, `StatusInitiated`, `"Initiated"`} {
|
|
if !strings.Contains(string(out), want) {
|
|
t.Fatalf("missing %q:\n%s", want, out)
|
|
}
|
|
}
|
|
}
|