|
| 1 | +/* |
| 2 | +* Copyright 2025 elementary, Inc. (https://elementary.io) |
| 3 | +* SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | +*/ |
| 5 | + |
| 6 | +/** |
| 7 | + * A simple test case class. To use it inherit from it and add test methods |
| 8 | + * in the constructor using {@link add_test}. Override {@link set_up} and {@link tear_down} |
| 9 | + * to provide per-test-method setup and teardown. Then add a `main()` function |
| 10 | + * and return the result of {@link run}. |
| 11 | + */ |
| 12 | +public abstract class Gala.TestCase : Object { |
| 13 | + public delegate void TestMethod (); |
| 14 | + |
| 15 | + public string name { get; construct; } |
| 16 | + |
| 17 | + private GLib.TestSuite suite; |
| 18 | + private Adaptor[] adaptors = new Adaptor[0]; |
| 19 | + |
| 20 | + construct { |
| 21 | + suite = new GLib.TestSuite (name); |
| 22 | + } |
| 23 | + |
| 24 | + public int run (string[] args) { |
| 25 | + Test.init (ref args); |
| 26 | + TestSuite.get_root ().add_suite (suite); |
| 27 | + return Test.run (); |
| 28 | + } |
| 29 | + |
| 30 | + protected void add_test (string name, owned TestMethod test) { |
| 31 | + var adaptor = new Adaptor (name, (owned) test, this); |
| 32 | + adaptors += adaptor; |
| 33 | + |
| 34 | + var test_case = new GLib.TestCase ( |
| 35 | + adaptor.name, |
| 36 | + adaptor.set_up, |
| 37 | + adaptor.run, |
| 38 | + adaptor.tear_down |
| 39 | + ); |
| 40 | + |
| 41 | + suite.add (test_case); |
| 42 | + } |
| 43 | + |
| 44 | + public virtual void set_up () { |
| 45 | + } |
| 46 | + |
| 47 | + public virtual void tear_down () { |
| 48 | + } |
| 49 | + |
| 50 | + public void assert_finalize_object<G> (ref G data) { |
| 51 | + unowned var weak_pointer = data; |
| 52 | + ((Object) data).add_weak_pointer (&weak_pointer); |
| 53 | + data = null; |
| 54 | + assert_null (weak_pointer); |
| 55 | + } |
| 56 | + |
| 57 | + private class Adaptor : Object { |
| 58 | + public string name { get; construct; } |
| 59 | + |
| 60 | + private TestMethod test; |
| 61 | + private TestCase test_case; |
| 62 | + |
| 63 | + public Adaptor (string name, owned TestMethod test, TestCase test_case) { |
| 64 | + Object (name: name); |
| 65 | + |
| 66 | + this.test = (owned) test; |
| 67 | + this.test_case = test_case; |
| 68 | + } |
| 69 | + |
| 70 | + public void set_up (void* fixture) { |
| 71 | + test_case.set_up (); |
| 72 | + } |
| 73 | + |
| 74 | + public void run (void* fixture) { |
| 75 | + test (); |
| 76 | + } |
| 77 | + |
| 78 | + public void tear_down (void* fixture) { |
| 79 | + test_case.tear_down (); |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments