aboutsummaryrefslogtreecommitdiffstats
path: root/engine/atf_result.cpp
blob: f99b28f9e96e0197b58cff871c089384df2c0fd9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
// Copyright 2010 The Kyua Authors.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "engine/atf_result.hpp"

#include <cstdlib>
#include <fstream>
#include <utility>

#include "engine/exceptions.hpp"
#include "model/test_result.hpp"
#include "utils/fs/path.hpp"
#include "utils/format/macros.hpp"
#include "utils/optional.ipp"
#include "utils/process/status.hpp"
#include "utils/sanity.hpp"
#include "utils/text/exceptions.hpp"
#include "utils/text/operations.ipp"

namespace fs = utils::fs;
namespace process = utils::process;
namespace text = utils::text;

using utils::none;
using utils::optional;


namespace {


/// Reads a file and flattens its lines.
///
/// The main purpose of this function is to simplify the parsing of a file
/// containing the result of a test.  Therefore, the return value carries
/// several assumptions.
///
/// \param input The stream to read from.
///
/// \return A pair (line count, contents) detailing how many lines where read
/// and their contents.  If the file contains a single line with no newline
/// character, the line count is 0.  If the file includes more than one line,
/// the lines are merged together and separated by the magic string
/// '&lt;&lt;NEWLINE&gt;&gt;'.
static std::pair< size_t, std::string >
read_lines(std::istream& input)
{
    std::pair< size_t, std::string > ret = std::make_pair(0, "");

    do {
        std::string line;
        std::getline(input, line);
        if (input.eof() && !line.empty()) {
            if (ret.first == 0)
                ret.second = line;
            else {
                ret.second += "<<NEWLINE>>" + line;
                ret.first++;
            }
        } else if (input.good()) {
            if (ret.first == 0)
                ret.second = line;
            else
                ret.second += "<<NEWLINE>>" + line;
            ret.first++;
        }
    } while (input.good());

    return ret;
}


/// Parses a test result that does not accept a reason.
///
/// \param status The result status name.
/// \param rest The rest of the line after the status name.
///
/// \return An object representing the test result.
///
/// \throw format_error If the result is invalid (i.e. rest is invalid).
///
/// \pre status must be "passed".
static engine::atf_result
parse_without_reason(const std::string& status, const std::string& rest)
{
    if (!rest.empty())
        throw engine::format_error(F("%s cannot have a reason") % status);
    PRE(status == "passed");
    return engine::atf_result(engine::atf_result::passed);
}


/// Parses a test result that needs a reason.
///
/// \param status The result status name.
/// \param rest The rest of the line after the status name.
///
/// \return An object representing the test result.
///
/// \throw format_error If the result is invalid (i.e. rest is invalid).
///
/// \pre status must be one of "broken", "expected_death", "expected_failure",
/// "expected_timeout", "failed" or "skipped".
static engine::atf_result
parse_with_reason(const std::string& status, const std::string& rest)
{
    using engine::atf_result;

    if (rest.length() < 3 || rest.substr(0, 2) != ": ")
        throw engine::format_error(F("%s must be followed by ': <reason>'") %
                                   status);
    const std::string reason = rest.substr(2);
    INV(!reason.empty());

    if (status == "broken")
        return atf_result(atf_result::broken, reason);
    else if (status == "expected_death")
        return atf_result(atf_result::expected_death, reason);
    else if (status == "expected_failure")
        return atf_result(atf_result::expected_failure, reason);
    else if (status == "expected_timeout")
        return atf_result(atf_result::expected_timeout, reason);
    else if (status == "failed")
        return atf_result(atf_result::failed, reason);
    else if (status == "skipped")
        return atf_result(atf_result::skipped, reason);
    else
        PRE_MSG(false, "Unexpected status");
}


/// Converts a string to an integer.
///
/// \param str The string containing the integer to convert.
///
/// \return The converted integer; none if the parsing fails.
static optional< int >
parse_int(const std::string& str)
{
    try {
        return utils::make_optional(text::to_type< int >(str));
    } catch (const text::value_error& e) {
        return none;
    }
}


/// Parses a test result that needs a reason and accepts an optional integer.
///
/// \param status The result status name.
/// \param rest The rest of the line after the status name.
///
/// \return The parsed test result if the data is valid, or a broken result if
/// the parsing failed.
///
/// \pre status must be one of "expected_exit" or "expected_signal".
static engine::atf_result
parse_with_reason_and_arg(const std::string& status, const std::string& rest)
{
    using engine::atf_result;

    std::string::size_type delim = rest.find_first_of(":(");
    if (delim == std::string::npos)
        throw engine::format_error(F("Invalid format for '%s' test case "
                                     "result; must be followed by '[(num)]: "
                                     "<reason>' but found '%s'") %
                                   status % rest);

    optional< int > arg;
    if (rest[delim] == '(') {
        const std::string::size_type delim2 = rest.find("):", delim);
        if (delim == std::string::npos)
            throw engine::format_error(F("Mismatched '(' in %s") % rest);

        const std::string argstr = rest.substr(delim + 1, delim2 - delim - 1);
        arg = parse_int(argstr);
        if (!arg)
            throw engine::format_error(F("Invalid integer argument '%s' to "
                                         "'%s' test case result") %
                                       argstr % status);
        delim = delim2 + 1;
    }

    const std::string reason = rest.substr(delim + 2);

    if (status == "expected_exit")
        return atf_result(atf_result::expected_exit, arg, reason);
    else if (status == "expected_signal")
        return atf_result(atf_result::expected_signal, arg, reason);
    else
        PRE_MSG(false, "Unexpected status");
}


/// Formats the termination status of a process to be used with validate_result.
///
/// \param status The status to format.
///
/// \return A string describing the status.
static std::string
format_status(const process::status& status)
{
    if (status.exited())
        return F("exited with code %s") % status.exitstatus();
    else if (status.signaled())
        return F("received signal %s%s") % status.termsig() %
            (status.coredump() ? " (core dumped)" : "");
    else
        return F("terminated in an unknown manner");
}


}  // anonymous namespace


/// Constructs a raw result with a type.
///
/// The reason and the argument are left uninitialized.
///
/// \param type_ The type of the result.
engine::atf_result::atf_result(const types type_) :
    _type(type_)
{
}


/// Constructs a raw result with a type and a reason.
///
/// The argument is left uninitialized.
///
/// \param type_ The type of the result.
/// \param reason_ The reason for the result.
engine::atf_result::atf_result(const types type_, const std::string& reason_) :
    _type(type_), _reason(reason_)
{
}


/// Constructs a raw result with a type, an optional argument and a reason.
///
/// \param type_ The type of the result.
/// \param argument_ The optional argument for the result.
/// \param reason_ The reason for the result.
engine::atf_result::atf_result(const types type_,
                               const utils::optional< int >& argument_,
                               const std::string& reason_) :
    _type(type_), _argument(argument_), _reason(reason_)
{
}


/// Parses an input stream to extract a test result.
///
/// If the parsing fails for any reason, the test result is 'broken' and it
/// contains the reason for the parsing failure.  Test cases that report results
/// in an inconsistent state cannot be trusted (e.g. the test program code may
/// have a bug), and thus why they are reported as broken instead of just failed
/// (which is a legitimate result for a test case).
///
/// \param input The stream to read from.
///
/// \return A generic representation of the result of the test case.
///
/// \throw format_error If the input is invalid.
engine::atf_result
engine::atf_result::parse(std::istream& input)
{
    const std::pair< size_t, std::string > data = read_lines(input);
    if (data.first == 0)
        throw format_error("Empty test result or no new line");
    else if (data.first > 1)
        throw format_error("Test result contains multiple lines: " +
                           data.second);
    else {
        const std::string::size_type delim = data.second.find_first_not_of(
            "abcdefghijklmnopqrstuvwxyz_");
        const std::string status = data.second.substr(0, delim);
        const std::string rest = data.second.substr(status.length());

        if (status == "broken")
            return parse_with_reason(status, rest);
        else if (status == "expected_death")
            return parse_with_reason(status, rest);
        else if (status == "expected_exit")
            return parse_with_reason_and_arg(status, rest);
        else if (status == "expected_failure")
            return parse_with_reason(status, rest);
        else if (status == "expected_signal")
            return parse_with_reason_and_arg(status, rest);
        else if (status == "expected_timeout")
            return parse_with_reason(status, rest);
        else if (status == "failed")
            return parse_with_reason(status, rest);
        else if (status == "passed")
            return parse_without_reason(status, rest);
        else if (status == "skipped")
            return parse_with_reason(status, rest);
        else
            throw format_error(F("Unknown test result '%s'") % status);
    }
}


/// Loads a test case result from a file.
///
/// \param file The file to parse.
///
/// \return The parsed test case result if all goes well.
///
/// \throw std::runtime_error If the file does not exist.
/// \throw engine::format_error If the contents of the file are bogus.
engine::atf_result
engine::atf_result::load(const fs::path& file)
{
    std::ifstream input(file.c_str());
    if (!input)
        throw std::runtime_error("Cannot open results file");
    else
        return parse(input);
}


/// Gets the type of the result.
///
/// \return A result type.
engine::atf_result::types
engine::atf_result::type(void) const
{
    return _type;
}


/// Gets the optional argument of the result.
///
/// \return The argument of the result if present; none otherwise.
const optional< int >&
engine::atf_result::argument(void) const
{
    return _argument;
}


/// Gets the optional reason of the result.
///
/// \return The reason of the result if present; none otherwise.
const optional< std::string >&
engine::atf_result::reason(void) const
{
    return _reason;
}


/// Checks whether the result should be reported as good or not.
///
/// \return True if the result can be considered "good", false otherwise.
bool
engine::atf_result::good(void) const
{
    switch (_type) {
    case atf_result::expected_death:
    case atf_result::expected_exit:
    case atf_result::expected_failure:
    case atf_result::expected_signal:
    case atf_result::expected_timeout:
    case atf_result::passed:
    case atf_result::skipped:
        return true;

    case atf_result::broken:
    case atf_result::failed:
        return false;

    default:
        UNREACHABLE;
    }
}


/// Reinterprets a raw result based on the termination status of the test case.
///
/// This reinterpretation ensures that the termination conditions of the program
/// match what is expected of the paticular result reported by the test program.
/// If such conditions do not match, the test program is considered bogus and is
/// thus reported as broken.
///
/// This is just a helper function for calculate_result(); the real result of
/// the test case cannot be inferred from apply() only.
///
/// \param status The exit status of the test program, or none if the test
/// program timed out.
///
/// \result The adjusted result.  The original result is transformed into broken
/// if the exit status of the program does not match our expectations.
engine::atf_result
engine::atf_result::apply(const optional< process::status >& status)
    const
{
    if (!status) {
        if (_type != atf_result::expected_timeout)
            return atf_result(atf_result::broken, "Test case body timed out");
        else
            return *this;
    }

    INV(status);
    switch (_type) {
    case atf_result::broken:
        return *this;

    case atf_result::expected_death:
        return *this;

    case atf_result::expected_exit:
        if (status.get().exited()) {
            if (_argument) {
                if (_argument.get() == status.get().exitstatus())
                    return *this;
                else
                    return atf_result(
                        atf_result::failed,
                        F("Test case expected to exit with code %s but got "
                          "code %s") %
                        _argument.get() % status.get().exitstatus());
            } else
                return *this;
        } else
              return atf_result(atf_result::broken, "Expected clean exit but " +
                                format_status(status.get()));

    case atf_result::expected_failure:
        if (status.get().exited() && status.get().exitstatus() == EXIT_SUCCESS)
            return *this;
        else
            return atf_result(atf_result::broken, "Expected failure should "
                              "have reported success but " +
                              format_status(status.get()));

    case atf_result::expected_signal:
        if (status.get().signaled()) {
            if (_argument) {
                if (_argument.get() == status.get().termsig())
                    return *this;
                else
                    return atf_result(
                        atf_result::failed,
                        F("Test case expected to receive signal %s but "
                          "got %s") %
                        _argument.get() % status.get().termsig());
            } else
                return *this;
        } else
            return atf_result(atf_result::broken, "Expected signal but " +
                              format_status(status.get()));

    case atf_result::expected_timeout:
        return atf_result(atf_result::broken, "Expected timeout but " +
                          format_status(status.get()));

    case atf_result::failed:
        if (status.get().exited() && status.get().exitstatus() == EXIT_FAILURE)
            return *this;
        else
            return atf_result(atf_result::broken, "Failed test case should "
                              "have reported failure but " +
                              format_status(status.get()));

    case atf_result::passed:
        if (status.get().exited() && status.get().exitstatus() == EXIT_SUCCESS)
            return *this;
        else
            return atf_result(atf_result::broken, "Passed test case should "
                              "have reported success but " +
                              format_status(status.get()));

    case atf_result::skipped:
        if (status.get().exited() && status.get().exitstatus() == EXIT_SUCCESS)
            return *this;
        else
            return atf_result(atf_result::broken, "Skipped test case should "
                              "have reported success but " +
                              format_status(status.get()));
    }

    UNREACHABLE;
}


/// Converts an internal result to the interface-agnostic representation.
///
/// \return A generic result instance representing this result.
model::test_result
engine::atf_result::externalize(void) const
{
    switch (_type) {
    case atf_result::broken:
        return model::test_result(model::test_result_broken, _reason.get());

    case atf_result::expected_death:
    case atf_result::expected_exit:
    case atf_result::expected_failure:
    case atf_result::expected_signal:
    case atf_result::expected_timeout:
        return model::test_result(model::test_result_expected_failure,
                                  _reason.get());

    case atf_result::failed:
        return model::test_result(model::test_result_failed, _reason.get());

    case atf_result::passed:
        return model::test_result(model::test_result_passed);

    case atf_result::skipped:
        return model::test_result(model::test_result_skipped, _reason.get());

    default:
        UNREACHABLE;
    }
}


/// Compares two raw results for equality.
///
/// \param other The result to compare to.
///
/// \return True if the two raw results are equal; false otherwise.
bool
engine::atf_result::operator==(const atf_result& other) const
{
    return _type == other._type && _argument == other._argument &&
        _reason == other._reason;
}


/// Compares two raw results for inequality.
///
/// \param other The result to compare to.
///
/// \return True if the two raw results are different; false otherwise.
bool
engine::atf_result::operator!=(const atf_result& other) const
{
    return !(*this == other);
}


/// Injects the object into a stream.
///
/// \param output The stream into which to inject the object.
/// \param object The object to format.
///
/// \return The output stream.
std::ostream&
engine::operator<<(std::ostream& output, const atf_result& object)
{
    std::string result_name;
    switch (object.type()) {
    case atf_result::broken: result_name = "broken"; break;
    case atf_result::expected_death: result_name = "expected_death"; break;
    case atf_result::expected_exit: result_name = "expected_exit"; break;
    case atf_result::expected_failure: result_name = "expected_failure"; break;
    case atf_result::expected_signal: result_name = "expected_signal"; break;
    case atf_result::expected_timeout: result_name = "expected_timeout"; break;
    case atf_result::failed: result_name = "failed"; break;
    case atf_result::passed: result_name = "passed"; break;
    case atf_result::skipped: result_name = "skipped"; break;
    }

    const optional< int >& argument = object.argument();

    const optional< std::string >& reason = object.reason();

    output << F("model::test_result{type=%s, argument=%s, reason=%s}")
        % text::quote(result_name, '\'')
        % (argument ? (F("%s") % argument.get()).str() : "none")
        % (reason ? text::quote(reason.get(), '\'') : "none");

    return output;
}


/// Calculates the user-visible result of a test case.
///
/// This function needs to perform magic to ensure that what the test case
/// reports as its result is what the user should really see: i.e. it adjusts
/// the reported status of the test to the exit conditions of its body and
/// cleanup parts.
///
/// \param body_status The termination status of the process that executed
///     the body of the test.  None if the body timed out.
/// \param results_file The path to the results file that the test case body is
///     supposed to have created.
///
/// \return The calculated test case result.
model::test_result
engine::calculate_atf_result(const optional< process::status >& body_status,
                             const fs::path& results_file)
{
    using engine::atf_result;

    atf_result result(atf_result::broken, "Unknown result");
    try {
        result = atf_result::load(results_file);
    } catch (const engine::format_error& error) {
        result = atf_result(atf_result::broken, error.what());
    } catch (const std::runtime_error& error) {
        if (body_status)
            result = atf_result(
                atf_result::broken, F("Premature exit; test case %s") %
                format_status(body_status.get()));
        else {
            // The test case timed out.  apply() handles this case later.
        }
    }

    result = result.apply(body_status);

    return result.externalize();
}