7eea2b7fb362bbd7190d7310bc78fce84f6a5749
[platform/core/test/security-tests.git] / src / framework / src / test_results_collector_xml.cpp
1 /*
2  * Copyright (c) 2014 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)
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 "--file=<filename> - name of file for output\n"
103            "                    default - results.xml\n";
104 }
105
106 void XmlCollector::Start()
107 {
108     Assert(!!m_fp && "File handle must not be null");
109     m_outputBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
110     m_outputBuffer.append("<testsuites>\n</testsuites>");
111     FlushOutput();
112 }
113
114 void XmlCollector::Finish()
115 {
116     std::size_t pos = GetCurrentGroupPosition();
117     if (std::string::npos != pos) {
118         GroupFinish(pos);
119         FlushOutput();
120     }
121 }
122
123 bool XmlCollector::ParseCollectorSpecificArg(const std::string& arg)
124 {
125     return ParseCollectorFileArg(arg, m_filename);
126 }
127
128 void XmlCollector::CollectResult(const std::string& id,
129                                  const FailStatus status,
130                                  const std::string& reason,
131                                  const bool& isPerformanceTest,
132                                  const std::chrono::system_clock::duration& performanceTime,
133                                  const std::chrono::system_clock::duration& performanceMaxTime)
134 {
135     m_resultBuffer.erase();
136     m_resultBuffer.append("\t\t<testcase name=\"");
137     m_resultBuffer.append(EscapeSpecialCharacters(id));
138     m_resultBuffer.append("\"");
139     switch (status) {
140     case FailStatus::NONE:
141         if (isPerformanceTest) {
142             if (performanceMaxTime <= std::chrono::microseconds::zero()) {
143                 m_resultBuffer.append(" status=\"OK\" time=\"");
144                 std::ostringstream ostr;
145                 ostr << performanceTime.count();
146                 m_resultBuffer.append(ostr.str());
147                 m_resultBuffer.append("\"/>\n");
148                 break;
149             } else {
150                 m_resultBuffer.append(" status=\"OK\" time=\"");
151                 std::ostringstream ostr;
152                 ostr << performanceTime.count();
153                 m_resultBuffer.append(ostr.str());
154                 m_resultBuffer.append("\" time_expected=\"");
155                 ostr.str("");
156                 ostr << performanceMaxTime.count();
157                 m_resultBuffer.append(ostr.str());
158                 m_resultBuffer.append("\"/>\n");
159                 break;
160             }
161         }
162         m_resultBuffer.append(" status=\"OK\"/>\n");
163         break;
164     case FailStatus::FAILED:
165         m_resultBuffer.append(" status=\"FAILED\">\n");
166         PrintfErrorMessage("FAILED", EscapeSpecialCharacters(reason), true);
167         m_resultBuffer.append("\t\t</testcase>\n");
168         break;
169     case FailStatus::IGNORED:
170         m_resultBuffer.append(" status=\"Ignored\">\n");
171         PrintfIgnoredMessage("Ignored", EscapeSpecialCharacters(
172                                  reason), true);
173         m_resultBuffer.append("\t\t</testcase>\n");
174         break;
175     default:
176         Assert(false && "Bad status");
177     }
178     std::size_t group_pos = GetCurrentGroupPosition();
179     if (std::string::npos == group_pos) {
180         ThrowMsg(DPL::Exception, "No current group set");
181     }
182
183     std::size_t last_case_pos = m_outputBuffer.find(
184             "<testcase name=\"unknown\"",
185             group_pos);
186     if (std::string::npos == last_case_pos) {
187         ThrowMsg(DPL::Exception, "Could not find SegFault test case");
188     }
189     m_outputBuffer.insert(last_case_pos - 2, m_resultBuffer);
190
191     m_stats.AddTest(status);
192
193     UpdateGroupHeader(group_pos,
194                       m_stats.GetTotal() + 1, // include SegFault
195                       m_stats.GetFailed() + 1, // include SegFault
196                       m_stats.GetIgnored());
197     FlushOutput();
198 }
199
200 std::size_t XmlCollector::GetCurrentGroupPosition() const
201 {
202     return m_outputBuffer.rfind("<testsuite ");
203 }
204
205 void XmlCollector::UpdateGroupHeader(const std::size_t groupPosition,
206                                      const unsigned int tests,
207                                      const unsigned int failures,
208                                      const unsigned int skipped)
209 {
210     UpdateElementAttribute(groupPosition, "tests", UIntToString(tests));
211     UpdateElementAttribute(groupPosition, "failures", UIntToString(failures));
212     UpdateElementAttribute(groupPosition, "skipped", UIntToString(skipped));
213 }
214
215 void XmlCollector::UpdateElementAttribute(const std::size_t elementPosition,
216                                           const std::string& name,
217                                           const std::string& value)
218 {
219     std::string pattern = name + "=\"";
220
221     std::size_t start = m_outputBuffer.find(pattern, elementPosition);
222     if (std::string::npos == start) {
223         ThrowMsg(DPL::Exception,
224                  "Could not find attribute " << name << " beginning");
225     }
226
227     std::size_t end = m_outputBuffer.find("\"", start + pattern.length());
228     if (std::string::npos == end) {
229         ThrowMsg(DPL::Exception,
230                  "Could not find attribute " << name << " end");
231     }
232
233     m_outputBuffer.replace(start + pattern.length(),
234                            end - start - pattern.length(),
235                            value);
236 }
237
238 std::string XmlCollector::UIntToString(const unsigned int value)
239 {
240     std::stringstream result;
241     result << value;
242     return result.str();
243 }
244
245 void XmlCollector::GroupFinish(const std::size_t groupPosition)
246 {
247     std::size_t segFaultStart =
248         m_outputBuffer.find("<testcase name=\"unknown\"", groupPosition);
249     if (std::string::npos == segFaultStart) {
250         ThrowMsg(DPL::Exception,
251                  "Could not find SegFault test case start position");
252     }
253     segFaultStart -= 2; // to erase tabs
254
255     std::string closeTag = "</testcase>";
256     std::size_t segFaultEnd = m_outputBuffer.find(closeTag, segFaultStart);
257     if (std::string::npos == segFaultEnd) {
258         ThrowMsg(DPL::Exception,
259                  "Could not find SegFault test case end position");
260     }
261     segFaultEnd += closeTag.length() + 1; // to erase new line
262
263     m_outputBuffer.erase(segFaultStart, segFaultEnd - segFaultStart);
264
265     UpdateGroupHeader(groupPosition,
266                       m_stats.GetTotal(),
267                       m_stats.GetFailed(),
268                       m_stats.GetIgnored());
269 }
270
271 void XmlCollector::FlushOutput()
272 {
273     int fd = fileno(m_fp.Get());
274     if (-1 == fd) {
275         const char* errStr = strerror(errno);
276         ThrowMsg(DPL::Exception, errStr);
277     }
278
279     if (-1 == TEMP_FAILURE_RETRY(ftruncate(fd, 0L))) {
280         const char* errStr = strerror(errno);
281         ThrowMsg(DPL::Exception, errStr);
282     }
283
284     if (-1 == TEMP_FAILURE_RETRY(fseek(m_fp.Get(), 0L, SEEK_SET))) {
285         const char* errStr = strerror(errno);
286         ThrowMsg(DPL::Exception, errStr);
287     }
288
289     if (m_outputBuffer.size() !=
290         fwrite(m_outputBuffer.c_str(), 1, m_outputBuffer.size(),
291                m_fp.Get()))
292     {
293         const char* errStr = strerror(errno);
294         ThrowMsg(DPL::Exception, errStr);
295     }
296
297     if (-1 == TEMP_FAILURE_RETRY(fflush(m_fp.Get()))) {
298         const char* errStr = strerror(errno);
299         ThrowMsg(DPL::Exception, errStr);
300     }
301 }
302
303 void XmlCollector::PrintfErrorMessage(const char* type,
304                                       const std::string& message,
305                                       bool verbosity)
306 {
307     if (verbosity) {
308         m_resultBuffer.append("\t\t\t<failure type=\"");
309         m_resultBuffer.append(EscapeSpecialCharacters(type));
310         m_resultBuffer.append("\" message=\"");
311         m_resultBuffer.append(EscapeSpecialCharacters(message));
312         m_resultBuffer.append("\"/>\n");
313     } else {
314         m_resultBuffer.append("\t\t\t<failure type=\"");
315         m_resultBuffer.append(EscapeSpecialCharacters(type));
316         m_resultBuffer.append("\"/>\n");
317     }
318 }
319
320 void XmlCollector::PrintfIgnoredMessage(const char* type,
321                                         const std::string& message,
322                                         bool verbosity)
323 {
324     if (verbosity) {
325         m_resultBuffer.append("\t\t\t<skipped type=\"");
326         m_resultBuffer.append(EscapeSpecialCharacters(type));
327         m_resultBuffer.append("\" message=\"");
328         m_resultBuffer.append(EscapeSpecialCharacters(message));
329         m_resultBuffer.append("\"/>\n");
330     } else {
331         m_resultBuffer.append("\t\t\t<skipped type=\"");
332         m_resultBuffer.append(EscapeSpecialCharacters(type));
333         m_resultBuffer.append("\"/>\n");
334     }
335 }
336
337 std::string XmlCollector::EscapeSpecialCharacters(std::string s)
338 {
339     for (unsigned int i = 0; i < s.size();) {
340         switch (s[i]) {
341         case '"':
342             s.erase(i, 1);
343             s.insert(i, "&quot;");
344             i += 6;
345             break;
346
347         case '&':
348             s.erase(i, 1);
349             s.insert(i, "&amp;");
350             i += 5;
351             break;
352
353         case '<':
354             s.erase(i, 1);
355             s.insert(i, "&lt;");
356             i += 4;
357             break;
358
359         case '>':
360             s.erase(i, 1);
361             s.insert(i, "&gt;");
362             i += 4;
363             break;
364
365         case '\'':
366             s.erase(i, 1);
367             s.insert(i, "&#39;");
368             i += 5;
369             break;
370         default:
371             ++i;
372             break;
373         }
374     }
375     return s;
376 }
377
378 } // namespace Test
379 } // namespace DPL