[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[RFC] Add assert statement to make unit testing easier for Poke code
From: |
Mohammad-Reza Nabipoor |
Subject: |
[RFC] Add assert statement to make unit testing easier for Poke code |
Date: |
Wed, 18 Nov 2020 00:46:11 +0330 |
Hi.
== Proposal
I suggest to support the following `assert` statements:
assert (condition);
assert (condition, message);
assert condition;
assert condition, message;
The parser will replace this statement with the following function call:
_pkl_assert (condition, message, lineinfo)
The `lineinfo` is a string containing the location of the statement:
"<filename>:<line>:<col>"
And implementation of `_pkl_assert` will something like this in `pkl-rt.pk`:
```poke
fun _pkl_assert = (uint<1> condition, string msg, string lineinfo)
{
if (cond)
return;
raise Exception {
code = EC_assert,
msg = "Assertion failed at " + lineinfo + (msg'length ? ": " + msg : ""),
exit_status = 1,
};
}
```
== Usage
The main use of `assert` in unit testing of Poke codes.
For example, this is the re-write of some of string tests in
`testsuite/poke.pkl/`:
```poke
type TestFn = () void;
type Test = struct
{
string name;
TestFn func; /* Currently doesn't work! error: invalid type in struct
field */
};
var tests = [
Test {
name = "index",
func = lambda void:
{
var n = 0;
assert ("foo"[n] == 102UB);
assert ("foo"[0] == 102UB);
var s = "bar";
n = 3;
assert (("foo" + s)[n] == 98UB);
assert (("foo" + "bar")[3] == 98UB);
}
},
Test {
name = "escape sequence",
func = lambda void:
{
var s = "\1\12\1234;\12==\n";
assert (s'length == 0o11UL);
assert (s[0] == 0o1UB);
assert (s[1] == 0o12UB);
assert (s[2] == 0o123UB);
assert (s[3:] == "4;\n==\n");
assert ("\\"[0] == 0x5c);
}
},
];
for (t in tests)
{
try t.func();
catch (Exception ex)
{
printf ("FAIL %s: %s\n", t.name, ex.msg);
continue;
}
print ("PASS " + t.name + "\n");
}
```
We also can define a pickle called `unittest` test to add some types and
functions
to make writing unit tests easier.
I think this is very useful Poke users. And very easy to implement.
The only thing `assert` give us is the location of the statement.
WDYT?
Any suggestion?
Regards,
Mohammad-Reza
- [RFC] Add assert statement to make unit testing easier for Poke code,
Mohammad-Reza Nabipoor <=