1package iso8601 2 3import ( 4 "testing" 5 "time" 6) 7 8func Test_parse_duration(t *testing.T) { 9 var dur time.Duration 10 var err error 11 12 // test with bad format 13 _, err = ParseDuration("asdf") 14 if err != ErrBadFormat { 15 t.Fatalf("Expected an ErrBadFormat") 16 } 17 18 // test with month 19 _, err = ParseDuration("P1M") 20 if err != ErrNoMonth { 21 t.Fatalf("Expected an ErrNoMonth") 22 } 23 24 // test with good full string 25 exp, _ := time.ParseDuration("51h4m5s") 26 dur, err = ParseDuration("P2DT3H4M5S") 27 if err != nil { 28 t.Fatalf("Did not expect err: %v", err) 29 } 30 if dur.Hours() != exp.Hours() { 31 t.Errorf("Expected %v hours, not %v", exp.Hours(), dur.Hours()) 32 } 33 if dur.Minutes() != exp.Minutes() { 34 t.Errorf("Expected %v minutes, not %v", exp.Hours(), dur.Minutes()) 35 } 36 if dur.Seconds() != exp.Seconds() { 37 t.Errorf("Expected 5 seconds, not %v", exp.Nanoseconds(), dur.Seconds()) 38 } 39 if dur.Nanoseconds() != exp.Nanoseconds() { 40 t.Error("Expected %v nanoseconds, not %v", exp.Nanoseconds(), dur.Nanoseconds()) 41 } 42 43 // test with good week string 44 dur, err = ParseDuration("P1W") 45 if err != nil { 46 t.Fatalf("Did not expect err: %v", err) 47 } 48 if dur.Hours() != 24*7 { 49 t.Errorf("Expected 168 hours, not %d", dur.Hours()) 50 } 51} 52 53func Test_format_duration(t *testing.T) { 54 // Test complex duration with hours, minutes, seconds 55 d := time.Duration(3701) * time.Second 56 s := FormatDuration(d) 57 if s != "PT1H1M41S" { 58 t.Fatalf("bad ISO 8601 duration string: %s", s) 59 } 60 61 // Test only minutes duration 62 d = time.Duration(20) * time.Minute 63 s = FormatDuration(d) 64 if s != "PT20M" { 65 t.Fatalf("bad ISO 8601 duration string for 20M: %s", s) 66 } 67 68 // Test only seconds 69 d = time.Duration(1) * time.Second 70 s = FormatDuration(d) 71 if s != "PT1S" { 72 t.Fatalf("bad ISO 8601 duration string for 1S: %s", s) 73 } 74 75 // Test negative duration (unsupported) 76 d = time.Duration(-1) * time.Second 77 s = FormatDuration(d) 78 if s != "PT0S" { 79 t.Fatalf("bad ISO 8601 duration string for negative: %s", s) 80 } 81} 82