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