1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "gtest/gtest.h"
18 
19 #include "DumpstateServer.h"
20 #include "ServiceDescriptor.h"
21 #include "ServiceSupplier.h"
22 #include "config/XmlServiceSupplier.h"
23 #include "config/dumpstate_hal_configuration_V1_0.h"
24 
25 #include <sstream>
26 #include <string>
27 
MakePrinterService(const std::string & msg)28 static ServiceDescriptor MakePrinterService(const std::string& msg) {
29     return ServiceDescriptor{msg, "/bin/echo -n \"" + msg + "\""};
30 }
31 
32 class AccumulatorConsumer : public ServiceDescriptor::OutputConsumer {
33   public:
Write(char * ptr,size_t len)34     void Write(char* ptr, size_t len) override { ss.write(ptr, len); }
35 
data()36     std::string data() { return ss.str(); }
37 
38   private:
39     std::stringstream ss;
40 };
41 
TEST(DumpstateServer,RunCommand)42 TEST(DumpstateServer, RunCommand) {
43     auto svc = MakePrinterService("hello world");
44     AccumulatorConsumer ac;
45     auto ok = svc.GetOutput(&ac);
46     ASSERT_FALSE(ok.has_value());
47     ASSERT_EQ("hello world", ac.data());
48 }
49 
TEST(Configuration,FromXmlBuffer)50 TEST(Configuration, FromXmlBuffer) {
51     std::string buf = R"foo(
52 <dumpstateHalConfiguration version="1.0">
53     <services>
54         <service name="svc1" command="cmd1"/>
55         <service name="svc2" command="cmd2 arg1"/>
56     </services>
57     <systemLogs>
58         <service name="log" command="logcat"/>
59     </systemLogs>
60 </dumpstateHalConfiguration>
61   )foo";
62 
63     auto supplier = XmlServiceSupplier::fromBuffer(buf);
64     ASSERT_TRUE(supplier.has_value());
65 
66     ASSERT_TRUE(supplier->GetSystemLogsService().has_value());
67     ASSERT_EQ(2, supplier->GetServices().size());
68 
69     ASSERT_STREQ("log", supplier->GetSystemLogsService()->name());
70     ASSERT_STREQ("logcat", supplier->GetSystemLogsService()->command());
71 
72     ASSERT_STREQ("svc1", supplier->GetServices().at(0).name());
73     ASSERT_STREQ("svc2", supplier->GetServices().at(1).name());
74 
75     ASSERT_STREQ("cmd1", supplier->GetServices().at(0).command());
76     ASSERT_STREQ("cmd2 arg1", supplier->GetServices().at(1).command());
77 }
78