testing.mx raw

   1  package testing
   2  
   3  import (
   4  	"fmt"
   5  	"os"
   6  )
   7  
   8  type T struct {
   9  	name   string
  10  	failed bool
  11  }
  12  
  13  func (t *T) Fatal(args ...any) {
  14  	fmt.Print("    ")
  15  	fmt.Println(args...)
  16  	t.failed = true
  17  	panic(testFailedPanic{})
  18  }
  19  
  20  func (t *T) Fatalf(format string, args ...any) {
  21  	fmt.Print("    ")
  22  	fmt.Printf(format, args...)
  23  	fmt.Println()
  24  	t.failed = true
  25  	panic(testFailedPanic{})
  26  }
  27  
  28  func (t *T) Error(args ...any) {
  29  	fmt.Print("    ")
  30  	fmt.Println(args...)
  31  	t.failed = true
  32  }
  33  
  34  func (t *T) Errorf(format string, args ...any) {
  35  	fmt.Print("    ")
  36  	fmt.Printf(format, args...)
  37  	fmt.Println()
  38  	t.failed = true
  39  }
  40  
  41  func (t *T) Log(args ...any) {
  42  	fmt.Print("    ")
  43  	fmt.Println(args...)
  44  }
  45  
  46  func (t *T) Logf(format string, args ...any) {
  47  	fmt.Print("    ")
  48  	fmt.Printf(format, args...)
  49  	fmt.Println()
  50  }
  51  
  52  func (t *T) Name() string {
  53  	return t.name
  54  }
  55  
  56  func (t *T) Skip(args ...any) {
  57  	fmt.Print("    SKIP: ")
  58  	fmt.Println(args...)
  59  	panic(testSkippedPanic{})
  60  }
  61  
  62  func (t *T) Helper() {}
  63  
  64  type testFailedPanic struct{}
  65  type testSkippedPanic struct{}
  66  
  67  type InternalTest struct {
  68  	Name string
  69  	F    func(*T)
  70  }
  71  
  72  func Main(tests []InternalTest) {
  73  	passed := 0
  74  	failed := 0
  75  	skipped := 0
  76  	for _, test := range tests {
  77  		t := &T{name: test.Name}
  78  		fmt.Println("=== RUN  ", test.Name)
  79  		func() {
  80  			defer func() {
  81  				r := recover()
  82  				if r != nil {
  83  					if _, ok := r.(testFailedPanic); ok {
  84  						return
  85  					}
  86  					if _, ok := r.(testSkippedPanic); ok {
  87  						return
  88  					}
  89  					fmt.Println("    panic:", r)
  90  					t.failed = true
  91  				}
  92  			}()
  93  			test.F(t)
  94  		}()
  95  		if t.failed {
  96  			fmt.Println("--- FAIL:", test.Name)
  97  			failed++
  98  		} else {
  99  			fmt.Println("--- PASS:", test.Name)
 100  			passed++
 101  		}
 102  	}
 103  	fmt.Println()
 104  	if failed > 0 {
 105  		fmt.Printf("FAIL: %d passed, %d failed, %d skipped\n", passed, failed, skipped)
 106  		os.Exit(1)
 107  	}
 108  	fmt.Printf("PASS: %d passed, %d skipped\n", passed, skipped)
 109  }
 110