Tests, that work!

This commit is contained in:
2019-10-31 18:56:10 -04:00
parent c52dadcf22
commit ed07a0855d
6 changed files with 152 additions and 10 deletions

View File

@@ -4,12 +4,20 @@ module BinaryOps(
)
where
import Data.Bits(xor,(.&.),(.|.))
import Data.Map.Strict(Map)
import qualified Data.Map.Strict as Map
import File
import Gen(toLit)
import Generators
import Language.Rust.Data.Ident
import Language.Rust.Data.Position
import Language.Rust.Quote
import Language.Rust.Syntax
import System.Random(RandomGen)
numTestCases :: Int
numTestCases = 3000
binaryOps :: File
binaryOps = File {
@@ -17,7 +25,7 @@ binaryOps = File {
outputName = "binary",
isUnsigned = True,
generator = declareBinaryOperators,
testCase = Nothing
testCase = Just generateTests
}
declareBinaryOperators :: Word -> SourceFile Span
@@ -29,6 +37,7 @@ declareBinaryOperators bitsize =
xorOps = generateBinOps "BitXor" struct_name "bitxor" BitXorOp entries
baseNegationStmts = negationStatements "self" entries
refNegationStmts = negationStatements "output" entries
testFileLit = Lit [] (Str (testFile bitsize) Cooked Unsuffixed mempty) mempty
in [sourceFile|
use core::ops::{BitAnd,BitAndAssign};
use core::ops::{BitOr,BitOrAssign};
@@ -37,6 +46,8 @@ declareBinaryOperators bitsize =
#[cfg(test)]
use crate::CryptoNum;
#[cfg(test)]
use crate::testing::{build_test_path,run_test};
#[cfg(test)]
use quickcheck::quickcheck;
use super::$$struct_name;
@@ -109,6 +120,33 @@ declareBinaryOperators bitsize =
(&a | $$struct_name::zero()) == a
}
}
#[cfg(test)]
#[allow(non_snake_case)]
#[test]
fn KATs() {
run_test(build_test_path("binary", $$(testFileLit)), 6, |case| {
let (neg0, xbytes) = case.get("x").unwrap();
let (neg1, ybytes) = case.get("y").unwrap();
let (neg2, abytes) = case.get("a").unwrap();
let (neg3, obytes) = case.get("o").unwrap();
let (neg4, ebytes) = case.get("e").unwrap();
let (neg5, nbytes) = case.get("n").unwrap();
assert!(!neg0 && !neg1 && !neg2 && !neg3 && !neg4 && !neg5);
let x = $$struct_name::from_bytes(&xbytes);
let y = $$struct_name::from_bytes(&ybytes);
let a = $$struct_name::from_bytes(&abytes);
let o = $$struct_name::from_bytes(&obytes);
let e = $$struct_name::from_bytes(&ebytes);
let n = $$struct_name::from_bytes(&nbytes);
assert_eq!(a, &x & &y);
assert_eq!(o, &x | &y);
assert_eq!(e, &x ^ &y);
assert_eq!(n, !x);
});
}
|]
negationStatements :: String -> Word -> [Stmt Span]
@@ -201,3 +239,17 @@ generateAllTheVariants traitname func sname oper entries = [
Semi (AssignOp [] oper [expr| $$(left).value[$$(i)] |]
[expr| $$(right).value[$$(i)] |]
mempty) mempty
generateTests :: RandomGen g => Word -> g -> [Map String String]
generateTests size g = go g numTestCases
where
go _ 0 = []
go g0 i =
let (x, g1) = generateNum g0 size
(y, g2) = generateNum g1 size
tcase = Map.fromList [("x", showX x), ("y", showX y),
("a", showX (x .&. y)),
("o", showX (x .|. y)),
("e", showX (x `xor` y)),
("n", showX ( ((2 ^ size) - 1) `xor` x ))]
in tcase : go g2 (i - 1)