summaryrefslogtreecommitdiffstats
path: root/contrib/atf/atf-c++/tests.cpp
blob: cdc0dfbad4f3e9946d5d3161dd32759ef1c68486 (plain)
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//
// Automated Testing Framework (atf)
//
// Copyright (c) 2007 The NetBSD Foundation, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. 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.
//
// THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
//

extern "C" {
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
}

#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <vector>

extern "C" {
#include "atf-c/error.h"
#include "atf-c/tc.h"
#include "atf-c/utils.h"
}

#include "tests.hpp"

#include "detail/application.hpp"
#include "detail/env.hpp"
#include "detail/exceptions.hpp"
#include "detail/fs.hpp"
#include "detail/parser.hpp"
#include "detail/sanity.hpp"
#include "detail/text.hpp"

namespace impl = atf::tests;
namespace detail = atf::tests::detail;
#define IMPL_NAME "atf::tests"

// ------------------------------------------------------------------------
// The "atf_tp_writer" class.
// ------------------------------------------------------------------------

detail::atf_tp_writer::atf_tp_writer(std::ostream& os) :
    m_os(os),
    m_is_first(true)
{
    atf::parser::headers_map hm;
    atf::parser::attrs_map ct_attrs;
    ct_attrs["version"] = "1";
    hm["Content-Type"] = atf::parser::header_entry("Content-Type",
        "application/X-atf-tp", ct_attrs);
    atf::parser::write_headers(hm, m_os);
}

void
detail::atf_tp_writer::start_tc(const std::string& ident)
{
    if (!m_is_first)
        m_os << "\n";
    m_os << "ident: " << ident << "\n";
    m_os.flush();
}

void
detail::atf_tp_writer::end_tc(void)
{
    if (m_is_first)
        m_is_first = false;
}

void
detail::atf_tp_writer::tc_meta_data(const std::string& name,
                                    const std::string& value)
{
    PRE(name != "ident");
    m_os << name << ": " << value << "\n";
    m_os.flush();
}

// ------------------------------------------------------------------------
// Free helper functions.
// ------------------------------------------------------------------------

bool
detail::match(const std::string& regexp, const std::string& str)
{
    return atf::text::match(str, regexp);
}

// ------------------------------------------------------------------------
// The "tc" class.
// ------------------------------------------------------------------------

static std::map< atf_tc_t*, impl::tc* > wraps;
static std::map< const atf_tc_t*, const impl::tc* > cwraps;

struct impl::tc_impl : atf::utils::noncopyable {
    std::string m_ident;
    atf_tc_t m_tc;
    bool m_has_cleanup;

    tc_impl(const std::string& ident, const bool has_cleanup) :
        m_ident(ident),
        m_has_cleanup(has_cleanup)
    {
    }

    static void
    wrap_head(atf_tc_t *tc)
    {
        std::map< atf_tc_t*, impl::tc* >::iterator iter = wraps.find(tc);
        INV(iter != wraps.end());
        (*iter).second->head();
    }

    static void
    wrap_body(const atf_tc_t *tc)
    {
        std::map< const atf_tc_t*, const impl::tc* >::const_iterator iter =
            cwraps.find(tc);
        INV(iter != cwraps.end());
        try {
            (*iter).second->body();
        } catch (const std::exception& e) {
            (*iter).second->fail("Caught unhandled exception: " + std::string(
                                     e.what()));
        } catch (...) {
            (*iter).second->fail("Caught unknown exception");
        }
    }

    static void
    wrap_cleanup(const atf_tc_t *tc)
    {
        std::map< const atf_tc_t*, const impl::tc* >::const_iterator iter =
            cwraps.find(tc);
        INV(iter != cwraps.end());
        (*iter).second->cleanup();
    }
};

impl::tc::tc(const std::string& ident, const bool has_cleanup) :
    pimpl(new tc_impl(ident, has_cleanup))
{
}

impl::tc::~tc(void)
{
    cwraps.erase(&pimpl->m_tc);
    wraps.erase(&pimpl->m_tc);

    atf_tc_fini(&pimpl->m_tc);
}

void
impl::tc::init(const vars_map& config)
{
    atf_error_t err;

    utils::auto_array< const char * > array(
        new const char*[(config.size() * 2) + 1]);
    const char **ptr = array.get();
    for (vars_map::const_iterator iter = config.begin();
         iter != config.end(); iter++) {
         *ptr = (*iter).first.c_str();
         *(ptr + 1) = (*iter).second.c_str();
         ptr += 2;
    }
    *ptr = NULL;

    wraps[&pimpl->m_tc] = this;
    cwraps[&pimpl->m_tc] = this;

    err = atf_tc_init(&pimpl->m_tc, pimpl->m_ident.c_str(), pimpl->wrap_head,
        pimpl->wrap_body, pimpl->m_has_cleanup ? pimpl->wrap_cleanup : NULL,
        array.get());
    if (atf_is_error(err))
        throw_atf_error(err);
}

bool
impl::tc::has_config_var(const std::string& var)
    const
{
    return atf_tc_has_config_var(&pimpl->m_tc, var.c_str());
}

bool
impl::tc::has_md_var(const std::string& var)
    const
{
    return atf_tc_has_md_var(&pimpl->m_tc, var.c_str());
}

const std::string
impl::tc::get_config_var(const std::string& var)
    const
{
    return atf_tc_get_config_var(&pimpl->m_tc, var.c_str());
}

const std::string
impl::tc::get_config_var(const std::string& var, const std::string& defval)
    const
{
    return atf_tc_get_config_var_wd(&pimpl->m_tc, var.c_str(), defval.c_str());
}

const std::string
impl::tc::get_md_var(const std::string& var)
    const
{
    return atf_tc_get_md_var(&pimpl->m_tc, var.c_str());
}

const impl::vars_map
impl::tc::get_md_vars(void)
    const
{
    vars_map vars;

    char **array = atf_tc_get_md_vars(&pimpl->m_tc);
    try {
        char **ptr;
        for (ptr = array; *ptr != NULL; ptr += 2)
            vars[*ptr] = *(ptr + 1);
    } catch (...) {
        atf_utils_free_charpp(array);
        throw;
    }

    return vars;
}

void
impl::tc::set_md_var(const std::string& var, const std::string& val)
{
    atf_error_t err = atf_tc_set_md_var(&pimpl->m_tc, var.c_str(), val.c_str());
    if (atf_is_error(err))
        throw_atf_error(err);
}

void
impl::tc::run(const std::string& resfile)
    const
{
    atf_error_t err = atf_tc_run(&pimpl->m_tc, resfile.c_str());
    if (atf_is_error(err))
        throw_atf_error(err);
}

void
impl::tc::run_cleanup(void)
    const
{
    atf_error_t err = atf_tc_cleanup(&pimpl->m_tc);
    if (atf_is_error(err))
        throw_atf_error(err);
}

void
impl::tc::head(void)
{
}

void
impl::tc::cleanup(void)
    const
{
}

void
impl::tc::require_prog(const std::string& prog)
    const
{
    atf_tc_require_prog(prog.c_str());
}

void
impl::tc::pass(void)
{
    atf_tc_pass();
}

void
impl::tc::fail(const std::string& reason)
{
    atf_tc_fail("%s", reason.c_str());
}

void
impl::tc::fail_nonfatal(const std::string& reason)
{
    atf_tc_fail_nonfatal("%s", reason.c_str());
}

void
impl::tc::skip(const std::string& reason)
{
    atf_tc_skip("%s", reason.c_str());
}

void
impl::tc::check_errno(const char* file, const int line, const int exp_errno,
                      const char* expr_str, const bool result)
{
    atf_tc_check_errno(file, line, exp_errno, expr_str, result);
}

void
impl::tc::require_errno(const char* file, const int line, const int exp_errno,
                        const char* expr_str, const bool result)
{
    atf_tc_require_errno(file, line, exp_errno, expr_str, result);
}

void
impl::tc::expect_pass(void)
{
    atf_tc_expect_pass();
}

void
impl::tc::expect_fail(const std::string& reason)
{
    atf_tc_expect_fail("%s", reason.c_str());
}

void
impl::tc::expect_exit(const int exitcode, const std::string& reason)
{
    atf_tc_expect_exit(exitcode, "%s", reason.c_str());
}

void
impl::tc::expect_signal(const int signo, const std::string& reason)
{
    atf_tc_expect_signal(signo, "%s", reason.c_str());
}

void
impl::tc::expect_death(const std::string& reason)
{
    atf_tc_expect_death("%s", reason.c_str());
}

void
impl::tc::expect_timeout(const std::string& reason)
{
    atf_tc_expect_timeout("%s", reason.c_str());
}

// ------------------------------------------------------------------------
// The "tp" class.
// ------------------------------------------------------------------------

class tp : public atf::application::app {
public:
    typedef std::vector< impl::tc * > tc_vector;

private:
    static const char* m_description;

    bool m_lflag;
    atf::fs::path m_resfile;
    std::string m_srcdir_arg;
    atf::fs::path m_srcdir;

    atf::tests::vars_map m_vars;

    std::string specific_args(void) const;
    options_set specific_options(void) const;
    void process_option(int, const char*);

    void (*m_add_tcs)(tc_vector&);
    tc_vector m_tcs;

    void parse_vflag(const std::string&);
    void handle_srcdir(void);

    tc_vector init_tcs(void);

    enum tc_part {
        BODY,
        CLEANUP,
    };

    void list_tcs(void);
    impl::tc* find_tc(tc_vector, const std::string&);
    static std::pair< std::string, tc_part > process_tcarg(const std::string&);
    int run_tc(const std::string&);

public:
    tp(void (*)(tc_vector&));
    ~tp(void);

    int main(void);
};

const char* tp::m_description =
    "This is an independent atf test program.";

tp::tp(void (*add_tcs)(tc_vector&)) :
    app(m_description, "atf-test-program(1)", "atf(7)", false),
    m_lflag(false),
    m_resfile("/dev/stdout"),
    m_srcdir("."),
    m_add_tcs(add_tcs)
{
}

tp::~tp(void)
{
    for (tc_vector::iterator iter = m_tcs.begin();
         iter != m_tcs.end(); iter++) {
        impl::tc* tc = *iter;

        delete tc;
    }
}

std::string
tp::specific_args(void)
    const
{
    return "test_case";
}

tp::options_set
tp::specific_options(void)
    const
{
    using atf::application::option;
    options_set opts;
    opts.insert(option('l', "", "List test cases and their purpose"));
    opts.insert(option('r', "resfile", "The file to which the test program "
                                       "will write the results of the "
                                       "executed test case"));
    opts.insert(option('s', "srcdir", "Directory where the test's data "
                                      "files are located"));
    opts.insert(option('v', "var=value", "Sets the configuration variable "
                                         "`var' to `value'"));
    return opts;
}

void
tp::process_option(int ch, const char* arg)
{
    switch (ch) {
    case 'l':
        m_lflag = true;
        break;

    case 'r':
        m_resfile = atf::fs::path(arg);
        break;

    case 's':
        m_srcdir_arg = arg;
        break;

    case 'v':
        parse_vflag(arg);
        break;

    default:
        UNREACHABLE;
    }
}

void
tp::parse_vflag(const std::string& str)
{
    if (str.empty())
        throw std::runtime_error("-v requires a non-empty argument");

    std::vector< std::string > ws = atf::text::split(str, "=");
    if (ws.size() == 1 && str[str.length() - 1] == '=') {
        m_vars[ws[0]] = "";
    } else {
        if (ws.size() != 2)
            throw std::runtime_error("-v requires an argument of the form "
                                     "var=value");

        m_vars[ws[0]] = ws[1];
    }
}

void
tp::handle_srcdir(void)
{
    if (m_srcdir_arg.empty()) {
        m_srcdir = atf::fs::path(m_argv0).branch_path();
        if (m_srcdir.leaf_name() == ".libs")
            m_srcdir = m_srcdir.branch_path();
    } else
        m_srcdir = atf::fs::path(m_srcdir_arg);

    if (!atf::fs::exists(m_srcdir / m_prog_name))
        throw std::runtime_error("Cannot find the test program in the "
                                 "source directory `" + m_srcdir.str() + "'");

    if (!m_srcdir.is_absolute())
        m_srcdir = m_srcdir.to_absolute();

    m_vars["srcdir"] = m_srcdir.str();
}

tp::tc_vector
tp::init_tcs(void)
{
    m_add_tcs(m_tcs);
    for (tc_vector::iterator iter = m_tcs.begin();
         iter != m_tcs.end(); iter++) {
        impl::tc* tc = *iter;

        tc->init(m_vars);
    }
    return m_tcs;
}

//
// An auxiliary unary predicate that compares the given test case's
// identifier to the identifier stored in it.
//
class tc_equal_to_ident {
    const std::string& m_ident;

public:
    tc_equal_to_ident(const std::string& i) :
        m_ident(i)
    {
    }

    bool operator()(const impl::tc* tc)
    {
        return tc->get_md_var("ident") == m_ident;
    }
};

void
tp::list_tcs(void)
{
    tc_vector tcs = init_tcs();
    detail::atf_tp_writer writer(std::cout);

    for (tc_vector::const_iterator iter = tcs.begin();
         iter != tcs.end(); iter++) {
        const impl::vars_map vars = (*iter)->get_md_vars();

        {
            impl::vars_map::const_iterator iter2 = vars.find("ident");
            INV(iter2 != vars.end());
            writer.start_tc((*iter2).second);
        }

        for (impl::vars_map::const_iterator iter2 = vars.begin();
             iter2 != vars.end(); iter2++) {
            const std::string& key = (*iter2).first;
            if (key != "ident")
                writer.tc_meta_data(key, (*iter2).second);
        }

        writer.end_tc();
    }
}

impl::tc*
tp::find_tc(tc_vector tcs, const std::string& name)
{
    std::vector< std::string > ids;
    for (tc_vector::iterator iter = tcs.begin();
         iter != tcs.end(); iter++) {
        impl::tc* tc = *iter;

        if (tc->get_md_var("ident") == name)
            return tc;
    }
    throw atf::application::usage_error("Unknown test case `%s'",
                                        name.c_str());
}

std::pair< std::string, tp::tc_part >
tp::process_tcarg(const std::string& tcarg)
{
    const std::string::size_type pos = tcarg.find(':');
    if (pos == std::string::npos) {
        return std::make_pair(tcarg, BODY);
    } else {
        const std::string tcname = tcarg.substr(0, pos);

        const std::string partname = tcarg.substr(pos + 1);
        if (partname == "body")
            return std::make_pair(tcname, BODY);
        else if (partname == "cleanup")
            return std::make_pair(tcname, CLEANUP);
        else {
            using atf::application::usage_error;
            throw usage_error("Invalid test case part `%s'", partname.c_str());
        }
    }
}

int
tp::run_tc(const std::string& tcarg)
{
    const std::pair< std::string, tc_part > fields = process_tcarg(tcarg);

    impl::tc* tc = find_tc(init_tcs(), fields.first);

    if (!atf::env::has("__RUNNING_INSIDE_ATF_RUN") || atf::env::get(
        "__RUNNING_INSIDE_ATF_RUN") != "internal-yes-value")
    {
        std::cerr << m_prog_name << ": WARNING: Running test cases without "
            "atf-run(1) is unsupported\n";
        std::cerr << m_prog_name << ": WARNING: No isolation nor timeout "
            "control is being applied; you may get unexpected failures; see "
            "atf-test-case(4)\n";
    }

    try {
        switch (fields.second) {
        case BODY:
            tc->run(m_resfile.str());
            break;
        case CLEANUP:
            tc->run_cleanup();
            break;
        default:
            UNREACHABLE;
        }
        return EXIT_SUCCESS;
    } catch (const std::runtime_error& e) {
        std::cerr << "ERROR: " << e.what() << "\n";
        return EXIT_FAILURE;
    }
}

int
tp::main(void)
{
    using atf::application::usage_error;

    int errcode;

    handle_srcdir();

    if (m_lflag) {
        if (m_argc > 0)
            throw usage_error("Cannot provide test case names with -l");

        list_tcs();
        errcode = EXIT_SUCCESS;
    } else {
        if (m_argc == 0)
            throw usage_error("Must provide a test case name");
        else if (m_argc > 1)
            throw usage_error("Cannot provide more than one test case name");
        INV(m_argc == 1);

        errcode = run_tc(m_argv[0]);
    }

    return errcode;
}

namespace atf {
    namespace tests {
        int run_tp(int, char* const*, void (*)(tp::tc_vector&));
    }
}

int
impl::run_tp(int argc, char* const* argv, void (*add_tcs)(tp::tc_vector&))
{
    return tp(add_tcs).run(argc, argv);
}
OpenPOWER on IntegriCloud