| 1 | // Copyright 2013 Google Inc. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package getopt |
| 6 | |
| 7 | import ( |
| 8 | "fmt" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | var durationTests = []struct { |
| 15 | where string |
| 16 | in []string |
| 17 | d time.Duration |
| 18 | dur time.Duration |
| 19 | err string |
| 20 | }{ |
| 21 | { |
| 22 | loc(), |
| 23 | []string{}, |
| 24 | 17, 42, |
| 25 | "", |
| 26 | }, |
| 27 | { |
| 28 | loc(), |
| 29 | []string{"test", "-d", "1s", "--duration", "2s"}, |
| 30 | time.Second, 2 * time.Second, |
| 31 | "", |
| 32 | }, |
| 33 | { |
| 34 | loc(), |
| 35 | []string{"test", "-d1s", "-d2s"}, |
| 36 | 2 * time.Second, 42, |
| 37 | "", |
| 38 | }, |
| 39 | { |
| 40 | loc(), |
| 41 | []string{"test", "-d1"}, |
| 42 | 17, 42, |
| 43 | "test: time: missing unit in duration", |
| 44 | }, |
| 45 | { |
| 46 | loc(), |
| 47 | []string{"test", "--duration", "foo"}, |
| 48 | 17, 42, |
| 49 | "test: time: invalid duration", |
| 50 | }, |
| 51 | } |
| 52 | |
| 53 | func TestDuration(t *testing.T) { |
| 54 | for x, tt := range durationTests { |
| 55 | reset() |
| 56 | d := Duration('d', 17) |
| 57 | opt := DurationLong("duration", 0, 42) |
| 58 | if strings.Index(tt.where, ":-") > 0 { |
| 59 | tt.where = fmt.Sprintf("#%d", x) |
| 60 | } |
| 61 | |
| 62 | parse(tt.in) |
| 63 | if s := checkError(tt.err); s != "" { |
| 64 | t.Errorf("%s: %s", tt.where, s) |
| 65 | } |
| 66 | if got, want := *d, tt.d; got != want { |
| 67 | t.Errorf("%s: got %v, want %v", tt.where, got, want) |
| 68 | } |
| 69 | if got, want := *opt, tt.dur; got != want { |
| 70 | t.Errorf("%s: got %v, want %v", tt.where, got, want) |
| 71 | } |
| 72 | } |
| 73 | } |