Add PerformanceResult class
[platform/core/test/security-tests.git] / src / framework / src / test_results_collector_xml.cpp
1 /*
2  * Copyright (c) 2014-2015 Samsung Electronics Co., Ltd All Rights Reserved
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  * @file        test_results_collector_xml.cpp
18  * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
19  * @author      Marcin Niesluchowski (m.niesluchow@samsung.com)
20  * @version     1.0
21  * @brief       Source file containing XmlCollector class definition
22  */
23
24 #include <cerrno>
25 #include <cstdio>
26 #include <cstring>
27 #include <sstream>
28
29 #include <dpl/assert.h>
30 #include <dpl/exception.h>
31 #include <dpl/test/test_results_collector_commons.h>
32
33 #include "dpl/test/test_results_collector_xml.h"
34
35 namespace DPL {
36 namespace Test {
37
38 namespace {
39
40 const char *DEFAULT_XML_FILE_NAME = "results.xml";
41
42 }
43
44 XmlCollector::XmlCollector()
45     : m_filename(DEFAULT_XML_FILE_NAME), m_verbosity(true)
46 {
47 }
48
49 TestResultsCollectorBase* XmlCollector::Constructor()
50 {
51      return new XmlCollector();
52 }
53
54 void XmlCollector::CollectCurrentTestGroupName(const std::string& name)
55 {
56     std::size_t pos = GetCurrentGroupPosition();
57     if (std::string::npos != pos) {
58         GroupFinish(pos);
59         FlushOutput();
60         m_stats = Statistic();
61      }
62
63     pos = m_outputBuffer.find("</testsuites>");
64     if (std::string::npos == pos) {
65         ThrowMsg(DPL::Exception, "Could not find test suites closing tag");
66     }
67     GroupStart(pos, name);
68 }
69
70 void XmlCollector::GroupStart(const std::size_t pos, const std::string& name)
71 {
72     std::stringstream groupHeader;
73     groupHeader << "\n\t<testsuite";
74     groupHeader << " name=\"" << EscapeSpecialCharacters(name) << "\"";
75     groupHeader << R"( tests="1")"; // include SegFault
76     groupHeader << R"( failures="1")"; // include SegFault
77     groupHeader << R"( skipped="0")";
78     groupHeader << ">";
79
80     groupHeader << "\n\t\t<testcase name=\"unknown\" status=\"FAILED\">";
81     groupHeader <<
82     "\n\t\t\t<failure type=\"FAILED\" message=\"segmentation fault\"/>";
83     groupHeader << "\n\t\t</testcase>";
84
85     groupHeader << "\n\t</testsuite>";
86
87     m_outputBuffer.insert(pos - 1, groupHeader.str());
88 }
89
90 bool XmlCollector::Configure()
91 {
92     m_fp.Reset(fopen(m_filename.c_str(), "w"));
93     if (!m_fp) {
94         LogPedantic("Could not open file " << m_filename << " for writing");
95         return false;
96     }
97     return true;
98 }
99
100 std::string XmlCollector::CollectorSpecificHelp() const
101 {
102     return CollectorFileHelp(DEFAULT_XML_FILE_NAME) + COLLECTOR_NO_VERBOSE_HELP;
103 }
104
105 void XmlCollector::Start()
106 {
107     Assert(!!m_fp && "File handle must not be null");
108     m_outputBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
109     m_outputBuffer.append("<testsuites>\n</testsuites>");
110     FlushOutput();
111 }
112
113 void XmlCollector::Finish()
114 {
115     std::size_t pos = GetCurrentGroupPosition();
116     if (std::string::npos != pos) {
117         GroupFinish(pos);
118         FlushOutput();
119     }
120 }
121
122 bool XmlCollector::ParseCollectorSpecificArg(const std::string& arg)
123 {
124     return ParseCollectorFileArg(arg, m_filename) || ParseCollectorNoVerboseArg(arg, m_verbosity);
125 }
126
127 void XmlCollector::CollectResult(const std::string& id,
128                                  const FailStatus status,
129                                  const std::string& reason,
130                                  const ConstPerformanceResultPtr &performanceResult)
131 {
132     m_resultBuffer.erase();
133     m_resultBuffer.append("\t\t<testcase name=\"");
134     m_resultBuffer.append(EscapeSpecialCharacters(id));
135     m_resultBuffer.append("\"");
136
137     std::ostringstream ostr;
138     switch (status) {
139     case FailStatus::NONE:
140         if (!performanceResult) {
141             m_resultBuffer.append(" status=\"OK\"/>\n");
142             break;
143         }
144         if (!performanceResult->IsMaxDuration()) {
145             m_resultBuffer.append(" status=\"OK\" time=\"");
146             ostr << performanceResult->GetDuration().count();
147             m_resultBuffer.append(ostr.str());
148             m_resultBuffer.append("\"/>\n");
149             break;
150         }
151         m_resultBuffer.append(" status=\"OK\" time=\"");
152         ostr << performanceResult->GetDuration().count();
153         m_resultBuffer.append(ostr.str());
154         m_resultBuffer.append("\" time_expected=\"");
155         ostr.str("");
156         ostr << performanceResult->GetMaxDuration().count();
157         m_resultBuffer.append(ostr.str());
158         m_resultBuffer.append("\"/>\n");
159         break;
160     case FailStatus::FAILED:
161         m_resultBuffer.append(" status=\"FAILED\">\n");
162         PrintfErrorMessage("FAILED", EscapeSpecialCharacters(reason));
163         m_resultBuffer.append("\t\t</testcase>\n");
164         break;
165     case FailStatus::IGNORED:
166         m_resultBuffer.append(" status=\"Ignored\">\n");
167         PrintfIgnoredMessage("Ignored", EscapeSpecialCharacters(reason));
168         m_resultBuffer.append("\t\t</testcase>\n");
169         break;
170     default:
171         Assert(false && "Bad status");
172     }
173     std::size_t group_pos = GetCurrentGroupPosition();
174     if (std::string::npos == group_pos) {
175         ThrowMsg(DPL::Exception, "No current group set");
176     }
177
178     std::size_t last_case_pos = m_outputBuffer.find(
179             "<testcase name=\"unknown\"",
180             group_pos);
181     if (std::string::npos == last_case_pos) {
182         ThrowMsg(DPL::Exception, "Could not find SegFault test case");
183     }
184     m_outputBuffer.insert(last_case_pos - 2, m_resultBuffer);
185
186     m_stats.AddTest(status);
187
188     UpdateGroupHeader(group_pos,
189                       m_stats.GetTotal() + 1, // include SegFault
190                       m_stats.GetFailed() + 1, // include SegFault
191                       m_stats.GetIgnored());
192     FlushOutput();
193 }
194
195 std::size_t XmlCollector::GetCurrentGroupPosition() const
196 {
197     return m_outputBuffer.rfind("<testsuite ");
198 }
199
200 void XmlCollector::UpdateGroupHeader(const std::size_t groupPosition,
201                                      const unsigned int tests,
202                                      const unsigned int failures,
203                                      const unsigned int skipped)
204 {
205     UpdateElementAttribute(groupPosition, "tests", UIntToString(tests));
206     UpdateElementAttribute(groupPosition, "failures", UIntToString(failures));
207     UpdateElementAttribute(groupPosition, "skipped", UIntToString(skipped));
208 }
209
210 void XmlCollector::UpdateElementAttribute(const std::size_t elementPosition,
211                                           const std::string& name,
212                                           const std::string& value)
213 {
214     std::string pattern = name + "=\"";
215
216     std::size_t start = m_outputBuffer.find(pattern, elementPosition);
217     if (std::string::npos == start) {
218         ThrowMsg(DPL::Exception,
219                  "Could not find attribute " << name << " beginning");
220     }
221
222     std::size_t end = m_outputBuffer.find("\"", start + pattern.length());
223     if (std::string::npos == end) {
224         ThrowMsg(DPL::Exception,
225                  "Could not find attribute " << name << " end");
226     }
227
228     m_outputBuffer.replace(start + pattern.length(),
229                            end - start - pattern.length(),
230                            value);
231 }
232
233 std::string XmlCollector::UIntToString(const unsigned int value)
234 {
235     std::stringstream result;
236     result << value;
237     return result.str();
238 }
239
240 void XmlCollector::GroupFinish(const std::size_t groupPosition)
241 {
242     std::size_t segFaultStart =
243         m_outputBuffer.find("<testcase name=\"unknown\"", groupPosition);
244     if (std::string::npos == segFaultStart) {
245         ThrowMsg(DPL::Exception,
246                  "Could not find SegFault test case start position");
247     }
248     segFaultStart -= 2; // to erase tabs
249
250     std::string closeTag = "</testcase>";
251     std::size_t segFaultEnd = m_outputBuffer.find(closeTag, segFaultStart);
252     if (std::string::npos == segFaultEnd) {
253         ThrowMsg(DPL::Exception,
254                  "Could not find SegFault test case end position");
255     }
256     segFaultEnd += closeTag.length() + 1; // to erase new line
257
258     m_outputBuffer.erase(segFaultStart, segFaultEnd - segFaultStart);
259
260     UpdateGroupHeader(groupPosition,
261                       m_stats.GetTotal(),
262                       m_stats.GetFailed(),
263                       m_stats.GetIgnored());
264 }
265
266 void XmlCollector::FlushOutput()
267 {
268     int fd = fileno(m_fp.Get());
269     if (-1 == fd) {
270         const char* errStr = strerror(errno);
271         ThrowMsg(DPL::Exception, errStr);
272     }
273
274     if (-1 == TEMP_FAILURE_RETRY(ftruncate(fd, 0L))) {
275         const char* errStr = strerror(errno);
276         ThrowMsg(DPL::Exception, errStr);
277     }
278
279     if (-1 == TEMP_FAILURE_RETRY(fseek(m_fp.Get(), 0L, SEEK_SET))) {
280         const char* errStr = strerror(errno);
281         ThrowMsg(DPL::Exception, errStr);
282     }
283
284     if (m_outputBuffer.size() !=
285         fwrite(m_outputBuffer.c_str(), 1, m_outputBuffer.size(),
286                m_fp.Get()))
287     {
288         const char* errStr = strerror(errno);
289         ThrowMsg(DPL::Exception, errStr);
290     }
291
292     if (-1 == TEMP_FAILURE_RETRY(fflush(m_fp.Get()))) {
293         const char* errStr = strerror(errno);
294         ThrowMsg(DPL::Exception, errStr);
295     }
296 }
297
298 void XmlCollector::PrintfErrorMessage(const char* type, const std::string& message)
299 {
300     m_resultBuffer.append("\t\t\t<failure type=\"");
301     m_resultBuffer.append(EscapeSpecialCharacters(type));
302     if (m_verbosity) {
303         m_resultBuffer.append("\" message=\"");
304         m_resultBuffer.append(EscapeSpecialCharacters(message));
305     }
306     m_resultBuffer.append("\"/>\n");
307 }
308
309 void XmlCollector::PrintfIgnoredMessage(const char* type, const std::string& message)
310 {
311     m_resultBuffer.append("\t\t\t<skipped type=\"");
312     m_resultBuffer.append(EscapeSpecialCharacters(type));
313     if (m_verbosity) {
314         m_resultBuffer.append("\" message=\"");
315         m_resultBuffer.append(EscapeSpecialCharacters(message));
316     }
317     m_resultBuffer.append("\"/>\n");
318 }
319
320 std::string XmlCollector::EscapeSpecialCharacters(std::string s)
321 {
322     for (unsigned int i = 0; i < s.size();) {
323         switch (s[i]) {
324         case '"':
325             s.erase(i, 1);
326             s.insert(i, "&quot;");
327             i += 6;
328             break;
329
330         case '&':
331             s.erase(i, 1);
332             s.insert(i, "&amp;");
333             i += 5;
334             break;
335
336         case '<':
337             s.erase(i, 1);
338             s.insert(i, "&lt;");
339             i += 4;
340             break;
341
342         case '>':
343             s.erase(i, 1);
344             s.insert(i, "&gt;");
345             i += 4;
346             break;
347
348         case '\'':
349             s.erase(i, 1);
350             s.insert(i, "&#39;");
351             i += 5;
352             break;
353         default:
354             ++i;
355             break;
356         }
357     }
358     return s;
359 }
360
361 } // namespace Test
362 } // namespace DPL