TestCommandMocking is an invoked test helper that emulates expected behavior for predefined shell commands, erroring when unexpected conditions are encountered.
(t *testing.T)
| 1973 | |
| 1974 | // TestCommandMocking is an invoked test helper that emulates expected behavior for predefined shell commands, erroring when unexpected conditions are encountered. |
| 1975 | func TestCommandMocking(t *testing.T) { |
| 1976 | if os.Getenv("GH_WANT_HELPER_PROCESS_RICH") != "1" { |
| 1977 | return |
| 1978 | } |
| 1979 | |
| 1980 | jsonVar, ok := os.LookupEnv("GH_HELPER_PROCESS_RICH_COMMANDS") |
| 1981 | if !ok { |
| 1982 | fmt.Fprint(os.Stderr, "missing GH_HELPER_PROCESS_RICH_COMMANDS") |
| 1983 | // Exit 1 is used for empty key values in the git config. This is non-breaking in those use cases, |
| 1984 | // so this is returning a non-zero exit code to avoid suppressing this error for those use cases. |
| 1985 | os.Exit(16) |
| 1986 | } |
| 1987 | |
| 1988 | var commands mockedCommands |
| 1989 | if err := json.Unmarshal([]byte(jsonVar), &commands); err != nil { |
| 1990 | fmt.Fprint(os.Stderr, "failed to unmarshal GH_HELPER_PROCESS_RICH_COMMANDS") |
| 1991 | // Exit 1 is used for empty key values in the git config. This is non-breaking in those use cases, |
| 1992 | // so this is returning a non-zero exit code to avoid suppressing this error for those use cases. |
| 1993 | os.Exit(16) |
| 1994 | } |
| 1995 | |
| 1996 | // The discarded args are those for the go test binary itself, e.g. `-test.run=TestHelperProcessRich` |
| 1997 | realArgs := os.Args[3:] |
| 1998 | |
| 1999 | commandResult, ok := commands[args(strings.Join(realArgs, " "))] |
| 2000 | if !ok { |
| 2001 | fmt.Fprintf(os.Stderr, "unexpected command: %s\n", strings.Join(realArgs, " ")) |
| 2002 | // Exit 1 is used for empty key values in the git config. This is non-breaking in those use cases, |
| 2003 | // so this is returning a non-zero exit code to avoid suppressing this error for those use cases. |
| 2004 | os.Exit(16) |
| 2005 | } |
| 2006 | |
| 2007 | if commandResult.Stdout != "" { |
| 2008 | fmt.Fprint(os.Stdout, commandResult.Stdout) |
| 2009 | } |
| 2010 | |
| 2011 | if commandResult.Stderr != "" { |
| 2012 | fmt.Fprint(os.Stderr, commandResult.Stderr) |
| 2013 | } |
| 2014 | |
| 2015 | os.Exit(commandResult.ExitStatus) |
| 2016 | } |
| 2017 | |
| 2018 | func TestHelperProcess(t *testing.T) { |
| 2019 | if os.Getenv("GH_WANT_HELPER_PROCESS") != "1" { |