@@ -22,7 +22,7 @@ import (
22
22
"io/ioutil"
23
23
"net"
24
24
"os"
25
- "path"
25
+ "path/filepath "
26
26
"runtime"
27
27
"time"
28
28
@@ -119,11 +119,11 @@ func StartTestServer(t Logger, instanceOptions *TestServerInstanceOptions, custo
119
119
s .RecommendedOptions .SecureServing .ServerCert .CertDirectory = result .TmpDir
120
120
s .RecommendedOptions .SecureServing .ExternalAddress = s .RecommendedOptions .SecureServing .Listener .Addr ().(* net.TCPAddr ).IP // use listener addr although it is a loopback device
121
121
122
- _ , thisFile , _ , ok := runtime . Caller ( 0 )
123
- if ! ok {
124
- return result , fmt . Errorf ( "failed to get current file" )
122
+ pkgPath , err := pkgPath ( t )
123
+ if err != nil {
124
+ return result , err
125
125
}
126
- s .RecommendedOptions .SecureServing .ServerCert .FixtureDirectory = path .Join (path . Dir ( thisFile ) , "testdata" )
126
+ s .RecommendedOptions .SecureServing .ServerCert .FixtureDirectory = filepath .Join (pkgPath , "testdata" )
127
127
128
128
if storageConfig != nil {
129
129
s .RecommendedOptions .Etcd .StorageConfig = * storageConfig
@@ -217,3 +217,36 @@ func createLocalhostListenerOnFreePort() (net.Listener, int, error) {
217
217
218
218
return ln , tcpAddr .Port , nil
219
219
}
220
+
221
+ // pkgPath returns the absolute file path to this package's directory. With go
222
+ // test, we can just look at the runtime call stack. However, bazel compiles go
223
+ // binaries with the -trimpath option so the simple approach fails however we
224
+ // can consult environment variables to derive the path.
225
+ //
226
+ // The approach taken here works for both go test and bazel on the assumption
227
+ // that if and only if trimpath is passed, we are running under bazel.
228
+ func pkgPath (t Logger ) (string , error ) {
229
+ _ , thisFile , _ , ok := runtime .Caller (0 )
230
+ if ! ok {
231
+ return "" , fmt .Errorf ("failed to get current file" )
232
+ }
233
+
234
+ pkgPath := filepath .Dir (thisFile )
235
+
236
+ // If we find bazel env variables, then -trimpath was passed so we need to
237
+ // construct the path from the environment.
238
+ if testSrcdir , testWorkspace := os .Getenv ("TEST_SRCDIR" ), os .Getenv ("TEST_WORKSPACE" ); testSrcdir != "" && testWorkspace != "" {
239
+ t .Logf ("Detected bazel env varaiables: TEST_SRCDIR=%q TEST_WORKSPACE=%q" , testSrcdir , testWorkspace )
240
+ pkgPath = filepath .Join (testSrcdir , testWorkspace , pkgPath )
241
+ }
242
+
243
+ // If the path is still not absolute, something other than bazel compiled
244
+ // with -trimpath.
245
+ if ! filepath .IsAbs (pkgPath ) {
246
+ return "" , fmt .Errorf ("can't construct an absolute path from %q" , pkgPath )
247
+ }
248
+
249
+ t .Logf ("Resolved testserver package path to: %q" , pkgPath )
250
+
251
+ return pkgPath , nil
252
+ }
0 commit comments