xref: /aosp_15_r20/external/bazel-skylib/tests/native_binary/assertdata.cc (revision bcb5dc7965af6ee42bf2f21341a2ec00233a8c8a)
1 // Copyright 2019 The Bazel Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <stdio.h>
16 
17 #include <memory>
18 #include <string>
19 
20 #include "tools/cpp/runfiles/runfiles.h"
21 
22 using bazel::tools::cpp::runfiles::Runfiles;
23 
main(int argc,char ** argv)24 int main(int argc, char **argv) {
25   std::string error;
26   std::unique_ptr<Runfiles> runfiles(Runfiles::Create(argv[0], &error));
27   if (runfiles == nullptr) {
28     fprintf(stderr, "ERROR(" __FILE__ ":%d): Could not init runfiles\n",
29             __LINE__);
30     return 1;
31   }
32 
33   char* workspace = getenv("TEST_WORKSPACE");
34   if (workspace == nullptr) {
35     fprintf(stderr, "ERROR(" __FILE__ ":%d): envvar TEST_WORKSPACE is undefined\n",
36             __LINE__);
37     return 1;
38   }
39 
40   // This should have runfiles, either from the binary itself or from the
41   // native_test.
42   std::string path =
43       runfiles->Rlocation(std::string(workspace) + "/tests/native_binary/testdata.txt");
44   FILE *f = fopen(path.c_str(), "rt");
45   if (!f) {
46     fprintf(stderr, "ERROR(" __FILE__ ":%d): Could not find runfile '%s'\n",
47             __LINE__, path.c_str());
48   }
49 
50   char buf[6];
51   size_t s = fread(buf, 1, 5, f);
52   fclose(f);
53   buf[5] = 0;
54   if (s != 5 || std::string("hello") != std::string(buf, 5)) {
55     fprintf(stderr, "ERROR(" __FILE__ ":%d): bad runfile contents (%s)\n",
56             __LINE__, buf);
57     return 1;
58   }
59 
60   return 0;
61 }
62