diff options
Diffstat (limited to 'test-chill/unit-tests')
33 files changed, 2554 insertions, 0 deletions
| diff --git a/test-chill/unit-tests/__init__.py b/test-chill/unit-tests/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/test-chill/unit-tests/__init__.py @@ -0,0 +1 @@ + diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_in.py b/test-chill/unit-tests/cpp_validate_prog/mm_in.py new file mode 100755 index 0000000..93eb080 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_in.py @@ -0,0 +1,9 @@ +#!/usr/bin/python + +import struct + +data = list(range(15)) + list(range(10)) + [0]*6 +bindata = ''.join([struct.pack('f',n) for n in data]) +with open('mm.in.data','wb') as f: +    f.write(bindata) + diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_one.cc b/test-chill/unit-tests/cpp_validate_prog/mm_one.cc new file mode 100644 index 0000000..6131ae1 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_one.cc @@ -0,0 +1,29 @@ +#define AN 3 +#define BM 2 +#define AMBN 5 + +/* + +<test name='mm_small'> + +procedure void mm( +    in  float[3][5] A = matrix([*,*],lambda i,j: random(-8,8)), +    in  float[5][2] B = matrix([*,*],lambda i,j: random(-8,8)), +    out float[3][2] C = matrix([*,*],lambda i,j: 0)) + +</test> + +*/ + +void mm(float A[AN][AMBN], float B[AMBN][BM], float C[AN][BM]) { +    int i; +    int j; +    int k; +    for(i = 0; i < AN; i++) { +        for(j = 0; j < BM; j++) { +            for(k = 0; k < AMBN; k++) { +                C[i][j] += A[i][k] * B[k][j]; +            } +        } +    } +} diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_one.testproc b/test-chill/unit-tests/cpp_validate_prog/mm_one.testproc new file mode 100644 index 0000000..a12a963 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_one.testproc @@ -0,0 +1,6 @@ + +procedure void mm( +    in  float[3][5] A = matrix([*,*],lambda i,j: random(-8,8)), +    in  float[5][2] B = matrix([*,*],lambda i,j: random(-8,8)), +    out float[3][2] C = matrix([*,*],lambda i,j: 0)) + diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_one_defines.cc b/test-chill/unit-tests/cpp_validate_prog/mm_one_defines.cc new file mode 100644 index 0000000..e35f189 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_one_defines.cc @@ -0,0 +1,25 @@ + +/* +<test name='mm_small' define="{'AN':3, 'BM':2, 'AMBN':5}"> + +procedure void mm( +    in  float[AN][AMBN] A = matrix([*,*],lambda i,j: random(-8,8)), +    in  float[AMBN][BM] B = matrix([*,*],lambda i,j: random(-8,8)), +    out float[AN][BM]   C = matrix([*,*],lambda i,j: 0)) + +</test> + +*/ + +void mm(float A[AN][AMBN], float B[AMBN][BM], float C[AN][BM]) { +    int i; +    int j; +    int k; +    for(i = 0; i < AN; i++) { +        for(j = 0; j < BM; j++) { +            for(k = 0; k < AMBN; k++) { +                C[i][j] += A[i][k] * B[k][j]; +            } +        } +    } +} diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_one_longer_main.cc b/test-chill/unit-tests/cpp_validate_prog/mm_one_longer_main.cc new file mode 100644 index 0000000..5b7e6c1 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_one_longer_main.cc @@ -0,0 +1,93 @@ +#define AN 3 +#define BM 2 +#define AMBN 5 +//#define PRINT + +#include <time.h> +#include <fstream> +#include <cstdio> + +/* + +<test name='mm_small'> + +procedure void mm( +    in  float[3][5] A = matrix([*,*],lambda i,j: random(-8,8)), +    in  float[5][2] B = matrix([*,*],lambda i,j: random(-8,8)), +    out float[3][2] C = matrix([*,*],lambda i,j: 0)) + +</test> + +*/ + +void mm(float A[AN][AMBN], float B[AMBN][BM], float C[AN][BM]) { +    int i; +    int j; +    int k; +    for(i = 0; i < AN; i++) { +        for(j = 0; j < BM; j++) { +            C[i][j] = 0; +            for(k = 0; k < AMBN; k++) { +                C[i][j] += A[i][k] * B[k][j]; +            } +        } +    } +} + +int main(int argc, char** argv) { +    float A[3][5] = {{0,1,2,3,4},{5,6,7,8,9},{10,11,12,13,14}}; +    float B[5][2] = {{0,1},{2,3},{4,5},{6,7},{8,9}}; +    float C[3][2] = {{0,0},{0,0},{0,0}}; +    timespec start_time; +    timespec end_time; +     +    if (argc == 3) { +        std::ifstream is(argv[1], std::ifstream::in | std::ifstream::binary); +        is.read((char*)A, 15*sizeof(float)); +        is.read((char*)B, 10*sizeof(float)); +        is.close(); +    } +     +    clock_gettime(CLOCK_REALTIME, &start_time); +    for(int i = 0; i < 10000; i++) { +        mm(A,B,C); +    } +    clock_gettime(CLOCK_REALTIME, &end_time); +     +    if (argc == 3) { +        std::ofstream os(argv[2], std::ofstream::out | std::ofstream::binary); +        os.write((char*)C, 6*sizeof(float)); +        os.close(); +    } +     +    #ifdef PRINT +    std::printf("A:\n"); +    for(int i = 0; i < 3; i++) { +        std::printf("["); +        for(int j = 0; j < 5; j++) { +            std::printf("%f,",A[i][j]); +        } +        std::printf("]\n"); +    } +    std::printf("B:\n"); +    for(int i = 0; i < 5; i++) { +        std::printf("["); +        for(int j = 0; j < 2; j++) { +            std::printf("%f,",B[i][j]); +        } +        std::printf("]\n"); +    } +    std::printf("C:\n"); +    for(int i = 0; i < 3; i++) { +        std::printf("["); +        for(int j = 0; j < 2; j++) { +            std::printf("%f,",C[i][j]); +        } +        std::printf("]\n"); +    } +    #else +    double time_diff = (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_nsec - start_time.tv_nsec)/1000000000.0; +    std::printf("(%f,)", time_diff); +    #endif +    return 0; +} diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_one_longer_wrong_main.cc b/test-chill/unit-tests/cpp_validate_prog/mm_one_longer_wrong_main.cc new file mode 100644 index 0000000..7d96248 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_one_longer_wrong_main.cc @@ -0,0 +1,93 @@ +#define AN 3 +#define BM 2 +#define AMBN 5 +//#define PRINT + +#include <time.h> +#include <fstream> +#include <cstdio> + +/* + +<test name='mm_small'> + +procedure void mm( +    in  float[3][5] A = matrix([*,*],lambda i,j: random(-8,8)), +    in  float[5][2] B = matrix([*,*],lambda i,j: random(-8,8)), +    out float[3][2] C = matrix([*,*],lambda i,j: 0)) + +</test> + +*/ + +void mm(float A[AN][AMBN], float B[AMBN][BM], float C[AN][BM]) { +    int i; +    int j; +    int k; +    for(i = 0; i < AN; i++) { +        for(j = 0; j < BM; j++) { +            C[i][j] = 0; +            for(k = 0; k < AMBN; k++) { +                C[i][j] += A[i][k] + B[k][j]; +            } +        } +    } +} + +int main(int argc, char** argv) { +    float A[3][5] = {{0,1,2,3,4},{5,6,7,8,9},{10,11,12,13,14}}; +    float B[5][2] = {{0,1},{2,3},{4,5},{6,7},{8,9}}; +    float C[3][2] = {{0,0},{0,0},{0,0}}; +    timespec start_time; +    timespec end_time; +     +    if (argc == 3) { +        std::ifstream is(argv[1], std::ifstream::in | std::ifstream::binary); +        is.read((char*)A, 15*sizeof(float)); +        is.read((char*)B, 10*sizeof(float)); +        is.close(); +    } +     +    clock_gettime(CLOCK_REALTIME, &start_time); +    for(int i = 0; i < 1000000; i++) { +        mm(A,B,C); +    } +    clock_gettime(CLOCK_REALTIME, &end_time); +     +    if (argc == 3) { +        std::ofstream os(argv[2], std::ofstream::out | std::ofstream::binary); +        os.write((char*)C, 6*sizeof(float)); +        os.close(); +    } +     +    #ifdef PRINT +    std::printf("A:\n"); +    for(int i = 0; i < 3; i++) { +        std::printf("["); +        for(int j = 0; j < 5; j++) { +            std::printf("%f,",A[i][j]); +        } +        std::printf("]\n"); +    } +    std::printf("B:\n"); +    for(int i = 0; i < 5; i++) { +        std::printf("["); +        for(int j = 0; j < 2; j++) { +            std::printf("%f,",B[i][j]); +        } +        std::printf("]\n"); +    } +    std::printf("C:\n"); +    for(int i = 0; i < 3; i++) { +        std::printf("["); +        for(int j = 0; j < 2; j++) { +            std::printf("%f,",C[i][j]); +        } +        std::printf("]\n"); +    } +    #else +    double time_diff = (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_nsec - start_time.tv_nsec)/1000000000.0; +    std::printf("(%f,)", time_diff); +    #endif +    return 0; +} diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_one_main.cc b/test-chill/unit-tests/cpp_validate_prog/mm_one_main.cc new file mode 100644 index 0000000..a03b505 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_one_main.cc @@ -0,0 +1,91 @@ +#define AN 3 +#define BM 2 +#define AMBN 5 +//#define PRINT + +#include <time.h> +#include <fstream> +#include <cstdio> + +/* + +<test name='mm_small'> + +procedure void mm( +    in  float[3][5] A = matrix([*,*],lambda i,j: random(-8,8)), +    in  float[5][2] B = matrix([*,*],lambda i,j: random(-8,8)), +    out float[3][2] C = matrix([*,*],lambda i,j: 0)) + +</test> + +*/ + +void mm(float A[AN][AMBN], float B[AMBN][BM], float C[AN][BM]) { +    int i; +    int j; +    int k; +    for(i = 0; i < AN; i++) { +        for(j = 0; j < BM; j++) { +            C[i][j] = 0; +            for(k = 0; k < AMBN; k++) { +                C[i][j] += A[i][k] * B[k][j]; +            } +        } +    } +} + +int main(int argc, char** argv) { +    float A[3][5] = {{0,1,2,3,4},{5,6,7,8,9},{10,11,12,13,14}}; +    float B[5][2] = {{0,1},{2,3},{4,5},{6,7},{8,9}}; +    float C[3][2] = {{0,0},{0,0},{0,0}}; +    timespec start_time; +    timespec end_time; +     +    if (argc == 3) { +        std::ifstream is(argv[1], std::ifstream::in | std::ifstream::binary); +        is.read((char*)A, 15*sizeof(float)); +        is.read((char*)B, 10*sizeof(float)); +        is.close(); +    } +     +    clock_gettime(CLOCK_REALTIME, &start_time); +    mm(A,B,C); +    clock_gettime(CLOCK_REALTIME, &end_time); +     +    if (argc == 3) { +        std::ofstream os(argv[2], std::ofstream::out | std::ofstream::binary); +        os.write((char*)C, 6*sizeof(float)); +        os.close(); +    } +     +    #ifdef PRINT +    std::printf("A:\n"); +    for(int i = 0; i < 3; i++) { +        std::printf("["); +        for(int j = 0; j < 5; j++) { +            std::printf("%f,",A[i][j]); +        } +        std::printf("]\n"); +    } +    std::printf("B:\n"); +    for(int i = 0; i < 5; i++) { +        std::printf("["); +        for(int j = 0; j < 2; j++) { +            std::printf("%f,",B[i][j]); +        } +        std::printf("]\n"); +    } +    std::printf("C:\n"); +    for(int i = 0; i < 3; i++) { +        std::printf("["); +        for(int j = 0; j < 2; j++) { +            std::printf("%f,",C[i][j]); +        } +        std::printf("]\n"); +    } +    #else +    double time_diff = (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_nsec - start_time.tv_nsec)/1000000000.0; +    std::printf("(%f,)", time_diff); +    #endif +    return 0; +} diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_one_out.cc b/test-chill/unit-tests/cpp_validate_prog/mm_one_out.cc new file mode 100644 index 0000000..6151301 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_one_out.cc @@ -0,0 +1,60 @@ +#include <time.h> +#include <fstream> +#include <cstdio> + + +#define AN 3 +#define BM 2 +#define AMBN 5 + +/* + +<test name='mm_small'> + +procedure void mm( +    in  float[3][5] A = matrix([*,*],lambda i,j: random(-8,8)), +    in  float[5][2] B = matrix([*,*],lambda i,j: random(-8,8)), +    out float[3][2] C = matrix([*,*],lambda i,j: 0)) + +</test> + +*/ + +void mm(float A[AN][AMBN], float B[AMBN][BM], float C[AN][BM]) { +    int i; +    int j; +    int k; +    for(i = 0; i < AN; i++) { +        for(j = 0; j < BM; j++) { +            for(k = 0; k < AMBN; k++) { +                C[i][j] += A[i][k] * B[k][j]; +            } +        } +    } +} + +int main(int argc, char** argv) { +    float A[3][5]; +    float B[5][2]; +    float C[3][2]; +    timespec start_time; +    timespec end_time; +     +    std::ifstream datafile_initialize(argv[1]); +    datafile_initialize.read((char*)A, 15*sizeof(float)); +    datafile_initialize.read((char*)B, 10*sizeof(float)); +    datafile_initialize.read((char*)C, 6*sizeof(float)); +    datafile_initialize.close(); +     +    clock_gettime(CLOCK_REALTIME, &start_time); +    mm(A,B,C); +    clock_gettime(CLOCK_REALTIME, &end_time); +     +    std::ofstream datafile_out(argv[2]); +    datafile_out.write((char*)C, 6*sizeof(float)); +    datafile_out.close(); +     +    double time_diff = (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_nsec - start_time.tv_nsec)/1000000000.0; +    std::printf("(%f,)", time_diff); +    return 0; +} diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_one_with.cc b/test-chill/unit-tests/cpp_validate_prog/mm_one_with.cc new file mode 100644 index 0000000..9cb0ae4 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_one_with.cc @@ -0,0 +1,30 @@ +#define AN 3 +#define BM 2 +#define AMBN 5 + +/* + +<test name='mm_small'> + +with {evendist2:lambda i,j: random(-8,8), zero2:lambda i,j: 0} +procedure void mm( +    in  float[3][5] A = matrix([*,*],evendist2), +    in  float[5][2] B = matrix([*,*],evendist2), +    out float[3][2] C = matrix([*,*],zero2)) + +</test> + +*/ + +void mm(float A[AN][AMBN], float B[AMBN][BM], float C[AN][BM]) { +    int i; +    int j; +    int k; +    for(i = 0; i < AN; i++) { +        for(j = 0; j < BM; j++) { +            for(k = 0; k < AMBN; k++) { +                C[i][j] += A[i][k] * B[k][j]; +            } +        } +    } +} diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_one_with.testproc b/test-chill/unit-tests/cpp_validate_prog/mm_one_with.testproc new file mode 100644 index 0000000..80bc841 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_one_with.testproc @@ -0,0 +1,7 @@ + +with {evendist2:lambda i,j: random(-8,8), zero2:lambda i,j: 0} +procedure void mm( +    in  float[3][5] A = matrix([*,*],evendist2), +    in  float[5][2] B = matrix([*,*],evendist2), +    out float[3][2] C = matrix([*,*],zero2)) + diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_one_with_defines.cc b/test-chill/unit-tests/cpp_validate_prog/mm_one_with_defines.cc new file mode 100644 index 0000000..77ce673 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_one_with_defines.cc @@ -0,0 +1,25 @@ + +/* +<test name='mm_small' define="{'AN':3, 'BM':2, 'AMBN':5}"> + +with {evendist2:lambda i,j: random(-8,8), zero2:lambda i,j: 0} +procedure void mm( +    in  float[AN][AMBN] A = matrix([*,*],evendist2), +    in  float[AMBN][BM] B = matrix([*,*],evendist2), +    out float[AN][BM]   C = matrix([*,*],zero2)) + +</test> +*/ + +void mm(float A[AN][AMBN], float B[AMBN][BM], float C[AN][BM]) { +    int i; +    int j; +    int k; +    for(i = 0; i < AN; i++) { +        for(j = 0; j < BM; j++) { +            for(k = 0; k < AMBN; k++) { +                C[i][j] += A[i][k] * B[k][j]; +            } +        } +    } +} diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_three_basic.cc b/test-chill/unit-tests/cpp_validate_prog/mm_three_basic.cc new file mode 100644 index 0000000..49df049 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_three_basic.cc @@ -0,0 +1,33 @@ +/* +<test name=small define="{'AN':2, 'AMBN':5, 'BM':3}"> +    procedure void mm( +        in  float[AN][AMBN] A = matrix([,],lambda i,j: i*AMBN + j), +        in  float[AMBN][BM] B = matrix([,],lambda i,j: i*BM + j), +        out float[AN][BM]   C = matrix([,],lambda i,j: 0)) +</test> + +<test name=medium define="{'AN':20, 'AMBN':50, 'BM':30}"> +    procedure void mm( +        in  float[AN][AMBN] A = matrix([,],lambda i,j: i*AMBN + j), +        in  float[AMBN][BM] B = matrix([,],lambda i,j: i*BM + j), +        out float[AN][BM]   C = matrix([,],lambda i,j: 0)) +</test> + +<test name=big define="{'AN':200, 'AMBN':500, 'BM':300}"> +    procedure void mm( +        in  float[AN][AMBN] A = matrix([,],lambda i,j: i*AMBN + j), +        in  float[AMBN][BM] B = matrix([,],lambda i,j: i*BM + j), +        out float[AN][BM]   C = matrix([,],lambda i,j: 0)) +</test> +*/ + +void mm(float A[AN][AMBN], float B[AMBN][BM], float C[AN][BM]) { +    for(int i = 0; i < AN; i++) { +        for(int j = 0; j < BM; j++) { +            C[i][j] = 0; +            for(int k = 0; k < AMBN; k++) { +                C[i][j] += A[i][k] * B[k][j]; +            } +        } +    } +} diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_three_basic.cc.data b/test-chill/unit-tests/cpp_validate_prog/mm_three_basic.cc.dataBinary files differ new file mode 100644 index 0000000..82c5ce6 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_three_basic.cc.data diff --git a/test-chill/unit-tests/cpp_validate_prog/mm_three_slow.cc b/test-chill/unit-tests/cpp_validate_prog/mm_three_slow.cc new file mode 100644 index 0000000..dd8c7e7 --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/mm_three_slow.cc @@ -0,0 +1,35 @@ +/* +<test name=small define="{'AN':2, 'AMBN':5, 'BM':3}"> +    procedure void mm( +        in  float[AN][AMBN] A = matrix([,],lambda i,j: i*AMBN + j), +        in  float[AMBN][BM] B = matrix([,],lambda i,j: i*BM + j), +        out float[AN][BM]   C = matrix([,],lambda i,j: 0)) +</test> + +<test name=medium define="{'AN':20, 'AMBN':50, 'BM':30}"> +    procedure void mm( +        in  float[AN][AMBN] A = matrix([,],lambda i,j: i*AMBN + j), +        in  float[AMBN][BM] B = matrix([,],lambda i,j: i*BM + j), +        out float[AN][BM]   C = matrix([,],lambda i,j: 0)) +</test> + +<test name=big define="{'AN':200, 'AMBN':500, 'BM':300}"> +    procedure void mm( +        in  float[AN][AMBN] A = matrix([,],lambda i,j: i*AMBN + j), +        in  float[AMBN][BM] B = matrix([,],lambda i,j: i*BM + j), +        out float[AN][BM]   C = matrix([,],lambda i,j: 0)) +</test> +*/ + +void mm(float A[AN][AMBN], float B[AMBN][BM], float C[AN][BM]) { +    for(int w = 0; w < 100; w++) { +        for(int i = 0; i < AN; i++) { +            for(int j = 0; j < BM; j++) { +                C[i][j] = 0; +                for(int k = 0; k < AMBN; k++) { +                    C[i][j] += A[i][k] * B[k][j]; +                } +            } +        } +    } +} diff --git a/test-chill/unit-tests/cpp_validate_prog/print_mm_out.py b/test-chill/unit-tests/cpp_validate_prog/print_mm_out.py new file mode 100755 index 0000000..fefbd2a --- /dev/null +++ b/test-chill/unit-tests/cpp_validate_prog/print_mm_out.py @@ -0,0 +1,10 @@ +#!/usr/bin/python + +import struct +import numpy as np + +with open('mm.out.data','rb') as f: +    data = f.read() + +mat = np.array([struct.unpack_from('f',data,n*4) for n in range(len(data)/4)]).reshape((3,2)) +print(mat) diff --git a/test-chill/unit-tests/cprog/Makefile b/test-chill/unit-tests/cprog/Makefile new file mode 100644 index 0000000..f5f2608 --- /dev/null +++ b/test-chill/unit-tests/cprog/Makefile @@ -0,0 +1,17 @@ +OBJS = $(patsubst %.cc, %.o, $(wildcard *.cc)) + +.PHONY: all +all: sorter + +$(OBJS): %.o: %.cc +	g++ -g -fprofile-arcs -ftest-coverage -c $< -o $@ + +.PHONY: sorter +sorter: $(OBJS) +	g++ -g -fprofile-arcs -ftest-coverage -o bin/sorter $(OBJS) + +.PHONY: clean +clean: +	rm -f *.o +	rm -f *.gcno *.gcda *.gcov +	rm -f bin/sorter diff --git a/test-chill/unit-tests/cprog/MergeSorter.cc b/test-chill/unit-tests/cprog/MergeSorter.cc new file mode 100644 index 0000000..6e747a3 --- /dev/null +++ b/test-chill/unit-tests/cprog/MergeSorter.cc @@ -0,0 +1,77 @@ +#include "MergeSorter.h" + +/* Python +def msort(lst, start, end, pindent = 0): +    if start == end: +        return +    center = start + ((end - start) // 2) +    print(' '*pindent + "SPLIT {}|{}".format(lst[start:center+1], lst[center+1:end+1])) +    msort(lst, start, center, pindent+1) +    msort(lst, center+1, end, pindent+1) +    left = list(lst[start:center+1]) +    right = list(lst[center+1:end+1]) +    print(' '*pindent + "MERGE {}|{}".format(lst[start:center+1], lst[center+1:end+1])) +    i,j = 0, 0 +    for k in range(start, end+1): +        if i >= len(left): +            lst[k] = right[j] +            j += 1 +            print(' '*(pindent+1) + 'pull j: {} {} {}'.format(lst[start:k+1], left[i:], right[j:])) +        elif j >= len(right): +            lst[k] = left[i] +            i += 1 +            print(' '*(pindent+1) + 'pull i: {} {} {}'.format(lst[start:k+1], left[i:], right[j:])) +        elif left[i] > right[j]: +            lst[k] = right[j] +            j += 1 +            print(' '*(pindent+1) + 'pull j: {} {} {}'.format(lst[start:k+1], left[i:], right[j:])) +        else: +            lst[k] = left[i] +            i += 1 +            print(' '*(pindent+1) + 'pull i: {} {} {}'.format(lst[start:k+1], left[i:], right[j:])) +    print(' '*pindent + "-- {}".format(lst[start:end+1])) +         + +if __name__ == '__main__': +    import random as r +    x = [int(r.random()*12) for i in range(7)] +    print(x) +    msort(x, 0, len(x)-1) +    print(x) +*/ + +static void mergesort(std::vector<int>& lst, int start, int end) { +    if(start == end) return; +    int center = start + (end-start)/2; +    mergesort(lst, start, center); +    mergesort(lst, center+1, end); +    std::vector<int> left = std::vector<int>(lst.begin()+start, lst.begin()+(center+1)); +    std::vector<int> right = std::vector<int>(lst.begin()+(center+1),lst.begin()+(end+1)); +    int i = 0; +    int j = 0; +    for(int k = start; k < (end+1); k++) { +        if (i >= left.size()) { +            lst[k] = right[j++]; +        } +        else if(j >= right.size()) { +            lst[k] = left[i++]; +        } +        else if(left[i] > right[j]) { +            lst[k] = right[j++]; +        } +        else { +            lst[k] = left[i++]; +        } +    } +} + +MergeSorter::MergeSorter() { +    this->name = std::string("mergesort"); +} + +MergeSorter::~MergeSorter() { +} + +void MergeSorter::sort(std::vector<int>& list) const { +    mergesort(list, 0, list.size()-1); +} diff --git a/test-chill/unit-tests/cprog/MergeSorter.h b/test-chill/unit-tests/cprog/MergeSorter.h new file mode 100644 index 0000000..e2ed391 --- /dev/null +++ b/test-chill/unit-tests/cprog/MergeSorter.h @@ -0,0 +1,14 @@ +#ifndef MERGE_SORTER_H +#define MERGE_SORTER_H + +#include <vector> +#include "Sorter.h" + +class MergeSorter : public Sorter { +public: +    MergeSorter(); +    virtual ~MergeSorter(); +    virtual void sort(std::vector<int>& list) const; +}; + +#endif diff --git a/test-chill/unit-tests/cprog/QuickSorter.cc b/test-chill/unit-tests/cprog/QuickSorter.cc new file mode 100644 index 0000000..3ade346 --- /dev/null +++ b/test-chill/unit-tests/cprog/QuickSorter.cc @@ -0,0 +1,83 @@ +#include "QuickSorter.h" + +/* Python + +def swap(l, i, k): +    v = l[i] +    l[i] = l[k] +    l[k] = v +    print(str(l)) + +def partition(l, start, end): +    print("PARTITION {} [{}:{}]".format(l, start, end)) +    p_value = l[end] +    p_index = end-1 +     +    for i in range(start, end): +        while(i < p_index and l[i] >= p_value): +            swap(l, i, p_index) +            p_index -= 1 +        while(i >= p_index and l[i] < p_value): +            swap(l, i, p_index) +            p_index += 1 +    swap(l, p_index, end) +    print("DONE {}|[{}]|{}:{}".format(l[start:p_index], l[p_index], l[p_index+1:end+1], p_value)) +    return p_index + +def qsort(l, i, k): +    if i < k: +        p = partition(l, i, k) +        qsort(l,i,p-1) +        qsort(l,p+1,k) + +if __name__ == "__main__": +    import random as r +    x = [int(r.random()*12) for i in range(12)] +    print(x) +    qsort(x, 0, len(x)-1) +    print(x) +     +*/ + +static void swap(std::vector<int>& list, int i, int k) { +    int v = list[i]; +    list[i] = list[k]; +    list[k] = v; +} + +static int partition(std::vector<int>& list, int i, int k) { +    int pivot_value = list[k]; +    int pivot_index = k - 1; +     +    for(int index = i; index < k; index++) { +        while((index < pivot_index) && (list[index] >= pivot_value)) { +            swap(list, index, pivot_index); +            pivot_index--; +        } +        while((index >= pivot_index) && (list[index] < pivot_value)) { +            swap(list, index, pivot_index); +            pivot_index++; +        } +    } +    swap(list, pivot_index, k); +    return pivot_index; +} + +static void quicksort(std::vector<int>& list, int i, int k) { +    if(i < k) { +        int p = partition(list, i, k); +        quicksort(list, i, p-1); +        quicksort(list, p+1, k); +    } +} + +QuickSorter::QuickSorter() { +    this->name = std::string("quicksort"); +} + +QuickSorter::~QuickSorter() { +} + +void QuickSorter::sort(std::vector<int>& list) const { +    quicksort(list, 0, list.size()-1); +} diff --git a/test-chill/unit-tests/cprog/QuickSorter.h b/test-chill/unit-tests/cprog/QuickSorter.h new file mode 100644 index 0000000..81919dd --- /dev/null +++ b/test-chill/unit-tests/cprog/QuickSorter.h @@ -0,0 +1,14 @@ +#ifndef QUICK_SORTER_H +#define QUICK_SORTER_H + +#include <vector> +#include "Sorter.h" + +class QuickSorter : public Sorter { +public: +    QuickSorter(); +    virtual ~QuickSorter(); +    virtual void sort(std::vector<int>& list) const; +}; + +#endif diff --git a/test-chill/unit-tests/cprog/Sorter.cc b/test-chill/unit-tests/cprog/Sorter.cc new file mode 100644 index 0000000..a1ae5ec --- /dev/null +++ b/test-chill/unit-tests/cprog/Sorter.cc @@ -0,0 +1,8 @@ +#include "Sorter.h" + +Sorter::Sorter() { +} + +Sorter::~Sorter() { +} + diff --git a/test-chill/unit-tests/cprog/Sorter.h b/test-chill/unit-tests/cprog/Sorter.h new file mode 100644 index 0000000..abf8f82 --- /dev/null +++ b/test-chill/unit-tests/cprog/Sorter.h @@ -0,0 +1,16 @@ +#ifndef SORTER_H +#define SORTER_H + +#include <string> +#include <vector> + +class Sorter { +public: +    Sorter(); +    virtual ~Sorter(); +     +    std::string name; +    virtual void sort(std::vector<int>& list) const = 0; +}; + +#endif diff --git a/test-chill/unit-tests/cprog/main.cc b/test-chill/unit-tests/cprog/main.cc new file mode 100644 index 0000000..3fe960b --- /dev/null +++ b/test-chill/unit-tests/cprog/main.cc @@ -0,0 +1,45 @@ +#include <cstdio> +#include <cstdlib> +#include <map> +#include <string> +#include <vector> + +#include "Sorter.h" +#include "QuickSorter.h" +#include "MergeSorter.h" +//#include "InsertionSorter.h" +//#include "ShellSorter.h" + +void read_vector(std::vector<int>& vec, int start, int stop, char** argv) { +    for(int i = start; i < stop; i++) { +        vec.push_back((int)strtol(argv[i],NULL,0)); +    } +} + +void print_vector(std::vector<int>& vec) { +    printf("["); +    for(std::vector<int>::iterator iter = vec.begin(); iter != vec.end(); iter++) { +        printf(" %d ", *iter); +    } +    printf("]\n"); +} + +void addsorter(std::map<std::string, Sorter*>& m, Sorter* s) { +    m[s->name] = s; +} + +int main(int argc, char** argv) { +    std::map<std::string, Sorter*> sorter_map; +    std::vector<int> vec; +     +    read_vector(vec, 2, argc, argv); +    print_vector(vec); +     +    addsorter(sorter_map, new QuickSorter()); +    addsorter(sorter_map, new MergeSorter()); +    //addsorter(sorter_map, new InsertionSorter()); +    //addsorter(sorter_map, new ShellSorter()); +    sorter_map[std::string(argv[1])]->sort(vec); +    print_vector(vec); +} + diff --git a/test-chill/unit-tests/test___main__.py b/test-chill/unit-tests/test___main__.py new file mode 100644 index 0000000..7a79417 --- /dev/null +++ b/test-chill/unit-tests/test___main__.py @@ -0,0 +1,205 @@ +import os +import unittest + +import testchill.gcov as gcov +import testchill.__main__ as main + + +def runtest(tc): +    tc.setUp() +    tc.run() +    tc.tearDown() + +class TestMain(unittest.TestCase): +    def setUp(self): +        self.chill_dev_src = os.getenv('CHILL_DEV_SRC') +        self.chill_release_src = os.getenv('CHILL_RELEASE_SRC') +        self.omega_dev_src = os.getenv('OMEGA_DEV_SRC') +        self.omega_release_src = os.getenv('OMEGA_RELEASE_SRC') +        self.staging_dir_bin = os.getenv('STAGING_DIR_BIN') +        self.staging_dir_wd = os.getenv('STAGING_DIR_WD') +     +    def test_main_parse_chillbuild(self): +        pass +     +    def test_main_parse_chill_dev(self): +        tclist = main.args_to_tclist('-b {} chill-testcase path/to/somescript.script path/to/somesrc.c'.format(self.staging_dir_bin).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +         +        self.assertEqual(tc.config.chill_dir, None) +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.build_cuda, False) +        self.assertEqual(tc.config.version, 'dev') +        self.assertEqual(tc.config.script_lang, 'script') +         +        self.assertEqual(tc.name, 'chill:somescript.script') +        self.assertEqual(tc.wd, os.getcwd()) +        self.assertEqual(tc.chill_bin, os.path.join(self.staging_dir_bin, 'chill')) +        self.assertEqual(tc.chill_script, 'somescript.script') +        self.assertEqual(tc.chill_src, 'somesrc.c') +        self.assertEqual(tc.chill_script_path, os.path.join(os.getcwd(), 'path/to/somescript.script')) +        self.assertEqual(tc.chill_src_path, os.path.join(os.getcwd(), 'path/to/somesrc.c')) +        self.assertEqual(tc.chill_gensrc, 'rose_somesrc.c') +     +    def test_main_parse_chill_lua_dev(self): +        tclist = main.args_to_tclist('-b {} chill-testcase path/to/somescript.lua path/to/somesrc.c'.format(self.staging_dir_bin).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +         +        self.assertEqual(tc.config.chill_dir, None) +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.build_cuda, False) +        self.assertEqual(tc.config.version, 'dev') +        self.assertEqual(tc.config.script_lang, 'lua') +         +        self.assertEqual(tc.name, 'chill-lua:somescript.lua') +        self.assertEqual(tc.wd, os.getcwd()) +        self.assertEqual(tc.chill_bin, os.path.join(self.staging_dir_bin, 'chill-lua')) +        self.assertEqual(tc.chill_script, 'somescript.lua') +        self.assertEqual(tc.chill_src, 'somesrc.c') +        self.assertEqual(tc.chill_script_path, os.path.join(os.getcwd(), 'path/to/somescript.lua')) +        self.assertEqual(tc.chill_src_path, os.path.join(os.getcwd(), 'path/to/somesrc.c')) +        self.assertEqual(tc.chill_gensrc, 'rose_somesrc.c') +     +    def test_main_parse_chill_python_dev(self): +        tclist = main.args_to_tclist('-b {} chill-testcase path/to/somescript.py path/to/somesrc.c'.format(self.staging_dir_bin).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +         +        self.assertEqual(tc.config.chill_dir, None) +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.build_cuda, False) +        self.assertEqual(tc.config.version, 'dev') +        self.assertEqual(tc.config.script_lang, 'python') +         +        self.assertEqual(tc.name, 'chill-python:somescript.py') +        self.assertEqual(tc.wd, os.getcwd()) +        self.assertEqual(tc.chill_bin, os.path.join(self.staging_dir_bin, 'chill-python')) +        self.assertEqual(tc.chill_script, 'somescript.py') +        self.assertEqual(tc.chill_src, 'somesrc.c') +        self.assertEqual(tc.chill_script_path, os.path.join(os.getcwd(), 'path/to/somescript.py')) +        self.assertEqual(tc.chill_src_path, os.path.join(os.getcwd(), 'path/to/somesrc.c')) +        self.assertEqual(tc.chill_gensrc, 'rose_somesrc.c') +     +    def test_main_parse_cudachill_dev(self): +        tclist = main.args_to_tclist('-b {} chill-testcase -u path/to/somescript.lua path/to/somesrc.c'.format(self.staging_dir_bin).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +         +        self.assertEqual(tc.config.chill_dir, None) +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.build_cuda, True) +        self.assertEqual(tc.config.version, 'dev') +        self.assertEqual(tc.config.script_lang, 'lua') +         +        self.assertEqual(tc.name, 'cuda-chill:somescript.lua') +        self.assertEqual(tc.wd, os.getcwd()) +        self.assertEqual(tc.chill_bin, os.path.join(self.staging_dir_bin, 'cuda-chill')) +        self.assertEqual(tc.chill_script, 'somescript.lua') +        self.assertEqual(tc.chill_src, 'somesrc.c') +        self.assertEqual(tc.chill_script_path, os.path.join(os.getcwd(), 'path/to/somescript.lua')) +        self.assertEqual(tc.chill_src_path, os.path.join(os.getcwd(), 'path/to/somesrc.c')) +        self.assertEqual(tc.chill_gensrc, 'rose_somesrc.cu') +     +    def test_main_parse_cudachill_python_dev(self): +        tclist = main.args_to_tclist('-b {} chill-testcase -u path/to/somescript.py path/to/somesrc.c'.format(self.staging_dir_bin).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +         +        self.assertEqual(tc.config.chill_dir, None) +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.build_cuda, True) +        self.assertEqual(tc.config.version, 'dev') +        self.assertEqual(tc.config.script_lang, 'python') +         +        self.assertEqual(tc.name, 'cuda-chill-python:somescript.py') +        self.assertEqual(tc.wd, os.getcwd()) +        self.assertEqual(tc.chill_bin, os.path.join(self.staging_dir_bin, 'cuda-chill-python')) +        self.assertEqual(tc.chill_script, 'somescript.py') +        self.assertEqual(tc.chill_src, 'somesrc.c') +        self.assertEqual(tc.chill_script_path, os.path.join(os.getcwd(), 'path/to/somescript.py')) +        self.assertEqual(tc.chill_src_path, os.path.join(os.getcwd(), 'path/to/somesrc.c')) +        self.assertEqual(tc.chill_gensrc, 'rose_somesrc.cu') +     +    def test_main_parse_chill_release(self): +        tclist = main.args_to_tclist('-b {} chill-testcase -v release path/to/somescript.script path/to/somesrc.c'.format(self.staging_dir_bin).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +        self.assertEqual(tc.name, 'chill-release:somescript.script') +        self.assertEqual(tc.wd, os.getcwd()) +        self.assertEqual(tc.chill_bin, os.path.join(self.staging_dir_bin, 'chill-release')) +        self.assertEqual(tc.chill_script, 'somescript.script') +        self.assertEqual(tc.chill_src, 'somesrc.c') +        self.assertEqual(tc.chill_script_path, os.path.join(os.getcwd(), 'path/to/somescript.script')) +        self.assertEqual(tc.chill_src_path, os.path.join(os.getcwd(), 'path/to/somesrc.c')) +        self.assertEqual(tc.chill_gensrc, 'rose_somesrc.c') +     +    def test_main_parse_chill_release(self): +        tclist = main.args_to_tclist('-b {} chill-testcase -uv release path/to/somescript.lua path/to/somesrc.c'.format(self.staging_dir_bin).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +        self.assertEqual(tc.name, 'cuda-chill-release:somescript.lua') +        self.assertEqual(tc.wd, os.getcwd()) +        self.assertEqual(tc.chill_bin, os.path.join(self.staging_dir_bin, 'cuda-chill-release')) +        self.assertEqual(tc.chill_script, 'somescript.lua') +        self.assertEqual(tc.chill_src, 'somesrc.c') +        self.assertEqual(tc.chill_script_path, os.path.join(os.getcwd(), 'path/to/somescript.lua')) +        self.assertEqual(tc.chill_src_path, os.path.join(os.getcwd(), 'path/to/somesrc.c')) +        self.assertEqual(tc.chill_gensrc, 'rose_somesrc.cu') +     +    def test_main_parse_chillbuild_dev(self): +        tclist = main.args_to_tclist('-b {} -C {} build-chill-testcase'.format(self.staging_dir_bin, self.chill_dev_src).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +        self.assertEqual(tc.name, 'chill') +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.chill_dir, self.chill_dev_src) +        self.assertEqual(tc.config.script_lang, 'script') +     +    def test_main_parse_chillbuild_lua_dev(self): +        tclist = main.args_to_tclist('-b {} -C {} build-chill-testcase -i lua'.format(self.staging_dir_bin, self.chill_dev_src).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +        self.assertEqual(tc.name, 'chill-lua') +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.chill_dir, self.chill_dev_src) +        self.assertEqual(tc.config.script_lang, 'lua') +     +    def test_main_parse_chillbuild_python_dev(self): +        tclist = main.args_to_tclist('-b {} -C {} build-chill-testcase -i python'.format(self.staging_dir_bin, self.chill_dev_src).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +        self.assertEqual(tc.name, 'chill-python') +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.chill_dir, self.chill_dev_src) +        self.assertEqual(tc.config.script_lang, 'python') +     +    def test_main_parse_chillbuild_cuda_dev(self): +        tclist = main.args_to_tclist('-b {} -C {} build-chill-testcase -u'.format(self.staging_dir_bin, self.chill_dev_src).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +        self.assertEqual(tc.name, 'cuda-chill') +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.chill_dir, self.chill_dev_src) +        self.assertEqual(tc.config.script_lang, 'lua') +     +    def test_main_parse_chillbuild_cuda_python_dev(self): +        tclist = main.args_to_tclist('-b {} -C {} build-chill-testcase -u -i python'.format(self.staging_dir_bin, self.chill_dev_src).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +        self.assertEqual(tc.name, 'cuda-chill-python') +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.chill_dir, self.chill_dev_src) +        self.assertEqual(tc.config.script_lang, 'python') +     +    def test_main_parse_chillbuild_release(self): +        tclist = main.args_to_tclist('-b {} -C {} build-chill-testcase -v release'.format(self.staging_dir_bin, self.chill_dev_src).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +        self.assertEqual(tc.name, 'chill-release') +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.chill_dir, self.chill_dev_src) +        self.assertEqual(tc.config.script_lang, 'script') +     +    def test_main_parse_chillbuild_cuda_release(self): +        tclist = main.args_to_tclist('-b {} -C {} build-chill-testcase -u -v release'.format(self.staging_dir_bin, self.chill_dev_src).split(), coverage_set=gcov.GcovSet()) +        tc = tclist[0] +        self.assertEqual(tc.name, 'cuda-chill-release') +        self.assertEqual(tc.config.bin_dir, self.staging_dir_bin) +        self.assertEqual(tc.config.chill_dir, self.chill_dev_src) +        self.assertEqual(tc.config.script_lang, 'lua') +     +    def test_main_tctree(self): +        tclist = main.args_to_tclist('batch test-cases/unit/chill-basic.tclist'.split(), coverage_set=gcov.GcovSet()) +        for tc in tclist: +            runtest(tc) + +     diff --git a/test-chill/unit-tests/test__cpp_validate_env.py b/test-chill/unit-tests/test__cpp_validate_env.py new file mode 100644 index 0000000..e0225cd --- /dev/null +++ b/test-chill/unit-tests/test__cpp_validate_env.py @@ -0,0 +1,377 @@ +import ast +import functools +import itertools +import pylang.debug +import random +import struct +import unittest + +import testchill +import testchill._cpp_validate_env as validate_env +import testchill.cpp_validate +import testchill.util + +## Support functions ## +class Point(object): +    def __init__(self, x, y): +        self.x = x +        self.y = y + +def _compile_and_run(expr, target_type, bindings): +    t = ast.fix_missing_locations(ast.Expression(expr.compile_expr(target_type))) +    return eval(compile(t, '<string>', 'eval'), bindings) + +def _compile_and_invoke(expr, target_type, bindings, args): +    t = ast.fix_missing_locations(ast.Expression(expr.compile_expr(target_type))) +    return (eval(compile(t, '<string>', 'eval'), bindings))(*args) + +def _expr_test(tc, expr, fv_bindings, rt_bindings, target_type, exp_freevars, exp_value): +    freevars = expr.getfreevars(fv_bindings) +    value = _compile_and_run(expr, target_type, rt_bindings) +    tc.assertEqual(exp_freevars, freevars) +    tc.assertEqual(exp_value, value) +    tc.assertEqual(target_type, type(value)) + +def _expr_test_list(tc, expr, fv_bindings, rt_bindings, target_type, exp_freevars, exp_value): +    freevars = expr.getfreevars(fv_bindings) +    value = _compile_and_run(expr, target_type, rt_bindings) +    tc.assertEqual(exp_freevars, freevars) +    tc.assertEqual(exp_value, value) +    tc.assertEqual(list, type(value)) + +def _expr_test_invoke(tc, expr, fv_bindings, rt_bindings, target_type, exp_freevars, invoke_args, exp_value): +    freevars = expr.getfreevars(fv_bindings) +    value = _compile_and_invoke(expr, target_type, rt_bindings, invoke_args) +    tc.assertEqual(exp_freevars, freevars) +    tc.assertEqual(exp_value, value) +    tc.assertEqual(target_type.exprtype, type(value)) + +def lambdatype(param_types, etype): +    return validate_env._pylambdatype(param_types, etype) + +def arraytype(dims, etype): +    return validate_env._pyarraytype(dims, etype) + + +## Test case class ## +class Test_CppValidateEnv(unittest.TestCase): +    def setUp(self): +        ### data for the abstract syntax tree ### +        _const_4 = validate_env._ConstantExpr('4') +        _const_3 = validate_env._ConstantExpr('3') +        _const_2 = validate_env._ConstantExpr('2') +        _const_0 = validate_env._ConstantExpr('0') +        _name_x = validate_env._NameExpr('x') +        _name_y = validate_env._NameExpr('y') +        _name_p = validate_env._NameExpr('p') +        _name_pow = validate_env._NameExpr('pow') +        _attr_px = validate_env._AttributeExpr(_name_p, 'x') +        _attr_py = validate_env._AttributeExpr(_name_p, 'y') +        _add_3_2 = validate_env._BinExpr(_const_3, '+', _const_2) +        _add_x_2 = validate_env._BinExpr(_name_x, '+', _const_2) +        _pow_x_2 = validate_env._BinExpr(_name_x, '**', _const_2) +         +        _name_i = validate_env._NameExpr('i') +        _lambda_i = validate_env._LambdaExpr(['i'],_name_i) +         +        _name_j = validate_env._NameExpr('j') +        _const_10 = validate_env._ConstantExpr('10') +        _mul_i_10 = validate_env._BinExpr(_name_i, '*', _const_10) +        _add_mul_i_10_j = validate_env._BinExpr(_mul_i_10, '+', _name_j) +        _lambda_ij = validate_env._LambdaExpr(['i','j'],_add_mul_i_10_j) +         +        self._ConstantExpr_test_data = [ +                (('3',), set(), dict(), int, set(), int(3)), +                (('3',), set(), dict(), float, set(), float(3)) +            ] +        self._NameExpr_test_data = [ +                (('x',), set(), {'x':3}, int, {'x'}, int(3)), +                (('x',), {'x'}, {'x':3}, int, set(), int(3)) +            ] +        self._AttributeExpr_test_data = [ +                ((validate_env._NameExpr('p'),'x'), set(), {'p':Point(3,0)}, int, {'p'}, int(3)), +                ((validate_env._NameExpr('p'),'x'), {'p'}, {'p':Point(3,0)}, int, set(), int(3)) +            ] +        self._BinExpr_test_data = [ +                ((_const_3, '+', _const_2), set(), dict(), int, set(), int(5)), +                ((_const_3, '+', _const_2), set(), dict(), float, set(), float(5)), +                ((_name_x, '+', _const_2), set(), {'x':3}, int, {'x'}, int(5)), +                ((_name_x, '+', _const_2), {'x'}, {'x':3}, int, set(), int(5)), +                ((_const_3, '+', _name_x), set(), {'x':2}, int, {'x'}, int(5)), +                ((_const_3, '+', _name_x), {'x'}, {'x':2}, int, set(), int(5)), +                ((_const_3, '-', _const_2), set(), dict(), int, set(), int(1)), +                ((_const_3, '*', _const_2), set(), dict(), int, set(), int(6)), +                ((_const_3, '/', _const_2), set(), dict(), int, set(), int(1)), +                ((_const_3, '**', _const_2), set(), dict(), int, set(), int(9)) +            ] +        self._UnaryExpr_test_data = [ +                (('-', _const_3), set(), dict(), int, set(), int(-3)), +                (('-', _add_3_2), set(), dict(), int, set(), int(-5)), +                (('-', _add_x_2), set(), {'x':3}, int, {'x'}, int(-5)), +                (('-', _add_x_2), {'x'}, {'x':3}, int, set(), int(-5)) +            ] +        self._LambdaExpr_test_data = [ +                (([],_const_3), set(), dict(), lambdatype([],int), set(), tuple(), int(3)), +                (([],_name_x), set(), {'x':3}, lambdatype([],int), {'x'}, tuple(), int(3)), +                ((['x'],_pow_x_2), set(), dict(), lambdatype([int],int), set(), (int(4),), int(16)) +            ] +        self._InvokeExpr_test_data = [ +                ((_name_pow,[_const_3, _const_2]), set(), dict(), int, {'pow'}, int(9)), +            ] +        self._MatrixGenerator_test_data = [ +                (([_const_2],_lambda_i), set(), {'_pyitertools': itertools}, arraytype([None],int), set(), [0, 1]), +                (([None],_lambda_i), set(), {'_pyitertools': itertools}, arraytype([_const_2],int), set(), [0, 1]), +                (([_const_2,_const_3],_lambda_ij), set(), {'_pyitertools': itertools}, arraytype([_const_2,_const_3], int), set(), [0, 1, 2, 10, 11, 12]), +                (([_const_2,_const_3],_lambda_ij), set(), {'_pyitertools': itertools}, arraytype([None,None], int), set(), [0, 1, 2, 10, 11, 12]), +                (([_const_2,None],_lambda_ij), set(), {'_pyitertools': itertools}, arraytype([None,_const_3], int), set(), [0, 1, 2, 10, 11, 12]), +                (([None,_const_3],_lambda_ij), set(), {'_pyitertools': itertools}, arraytype([_const_2,None], int), set(), [0, 1, 2, 10, 11, 12]), +                (([None,None],_lambda_ij), set(), {'_pyitertools': itertools}, arraytype([_const_2,_const_3], int), set(), [0, 1, 2, 10, 11, 12]), +                (([_name_x],_lambda_i), set(), {'_pyitertools': itertools, 'x':2}, arraytype([None],int), {'x'}, [0, 1]), +                (([None],_lambda_i), set(), {'_pyitertools': itertools, 'x':2}, arraytype([_name_x],int), set(), [0, 1]), +            ] +        self._RandomExpr_test_state = random.getstate() +        self._RandomExpr_test_data = [ +                ((_const_0,_const_4), set(), {'_pyrandom': random}, int, set(), int(random.random()*4)), +                ((_const_0,_name_x), set(), {'_pyrandom': random, 'x':4}, int, {'x'}, int(random.random()*4)), +                ((_name_x,_const_4), set(), {'_pyrandom': random, 'x':0}, int, {'x'}, int(random.random()*4)), +            ] +        ### data for data generating ### +        _name_ambn = validate_env._NameExpr('ambn') +        _name_an   = validate_env._NameExpr('an') +        _name_bm   = validate_env._NameExpr('bm') +        _name_even2 = validate_env._NameExpr('evendist2') +        _lambda_ij_0 = validate_env._LambdaExpr(['i','j'],_const_0) +        _matrix_2_an_ambn_even2 = validate_env._MatrixGenerator([_name_an,_name_ambn],_name_even2) +        _matrix_2_ambn_bm_even2 = validate_env._MatrixGenerator([_name_ambn,_name_bm],_name_even2) +        _matrix_2_an_bm_lambda_ij_0 = validate_env._MatrixGenerator([_name_an,_name_bm],_lambda_ij_0) +        _add_an_bm = validate_env._BinExpr(_name_an, '+', _name_bm) +        _int_type = validate_env._CppPrimitiveType.get_from_cppname('int') +        _float_type = validate_env._CppPrimitiveType.get_from_cppname('float') +        _float_ptr_type = validate_env._CppPointerType(_float_type) +        _param_A    = validate_env._Parameter('A',   _float_ptr_type,'in', _matrix_2_an_ambn_even2) +        _param_B    = validate_env._Parameter('B',   _float_ptr_type,'in', _matrix_2_ambn_bm_even2) +        _param_C    = validate_env._Parameter('C',   _float_ptr_type,'out',_matrix_2_an_bm_lambda_ij_0) +        _param_ambn = validate_env._Parameter('ambn',_int_type,      'in', _add_an_bm) +        _param_an   = validate_env._Parameter('an',  _int_type,      'in', _const_2) +        _param_bm   = validate_env._Parameter('bm',  _int_type,      'in', _const_3) +        self._Parameter_order_by_freevars_test_data = [ +                ([_param_A, _param_B, _param_C, _param_ambn, _param_an, _param_bm], ['an','bm','C','ambn','A','B']) +            ] +        _float_3_type = validate_env._CppArrayType(_float_type, [_const_3]) +        _float_3_2_type = validate_env._CppArrayType(_float_type, [_const_3,_const_2]) +        _name_N = validate_env._NameExpr('N') +        _float_N_type = validate_env._CppArrayType(_float_type, [_name_N]) +        _float_N_2_type = validate_env._CppArrayType(_float_type, [_name_N,_const_2]) +        self._CppType_statictype_test_data = [ +                ((_int_type, dict()), 'int'), +                ((_float_ptr_type, dict()), 'float*'), +                ((_float_3_type, dict()), 'float[3]'), +                ((_float_N_type, {'N': 3}), 'float[3]'), +                ((_float_N_2_type, {'N': 3}), 'float[3][2]') +            ] +        _int_ptr_type = validate_env._CppPointerType(_int_type) +        _int_ptr_ptr_type = validate_env._CppPointerType(_int_ptr_type) +        _int_3_type = validate_env._CppArrayType(_int_type, [_const_3]) +        _int_N_type = validate_env._CppArrayType(_int_type, [_name_N]) +        _int_3_2_type = validate_env._CppArrayType(_int_type, [_const_3, _const_2]) +        joinbytes = lambda b: functools.reduce(lambda a,v: a+v,b) +        self._CppType_formatdata_test_data = [ +                ((_int_type,         dict(), 3),                 ([1],     struct.pack('i',3))), +                ((_float_type,       dict(), float(3)),          ([1],     struct.pack('f',float(3)))), +                ((_int_3_type,       dict(), list(range(3))),    ([3],     joinbytes([struct.pack('i',i) for i in range(3)]))), +                ((_int_3_2_type,     dict(), list(range(6))),    ([3,2],   joinbytes([struct.pack('i',i) for i in range(6)]))), +                ((_int_ptr_type,     dict(), 3),                 ([1,1],   struct.pack('i',3))), +                ((_int_ptr_type,     dict(), list(range(3))),    ([3,1],   joinbytes([struct.pack('i',i) for i in range(3)]))), +                ((_int_ptr_ptr_type, dict(), list(range(3))),    ([3,1,1], joinbytes([struct.pack('i',i) for i in range(3)]))), +                ((_int_ptr_ptr_type, dict(), [[0,1,2],[3,4,5]]), ([2,3,1], joinbytes([struct.pack('i',i) for i in range(6)]))), +            ] +        evendist2 = lambda i,j: random.random() +        random.seed(0) +        self._Parameter_generatedata_test_state = random.getstate() +        if testchill.util.python_version_major == 2: +            self._Parameter_generatedata_test_data = [ +                    ((_param_A,    {'an':2, 'ambn':5,'evendist2':evendist2}), ('A', 'float*', [10, 1], '\x08,X?M\tB?)U\xd7>\xbc\x90\x84>\xe6\xe2\x02?\x87S\xcf>\x06\xa7H?\xceK\x9b>\x84\x04\xf4>\x86X\x15?')), +                    ((_param_B,    {'ambn':5, 'bm':3,'evendist2':evendist2}), ('B', 'float*', [15, 1], '\x16zh?(3\x01?\rM\x90>b|A?nM\x1e?^B\x80>!\xe5h?\xd4\x97{?fjO?Y\xf4f?\xaa\xcb\x9e>A\xd6:?D\x1af?\x92\x19/?\xb1\xbc\xf1>')), +                    ((_param_C,    {'an':2, 'bm':3, 'evendist2':evendist2}),  ('C', 'float*', [6, 1], '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')), +                    ((_param_ambn, {'an':2, 'bm':3}),                         ('ambn', 'int', [1], '\x05\x00\x00\x00')), +                    ((_param_an,   dict()),                                   ('an', 'int', [1], '\x02\x00\x00\x00')), +                    ((_param_bm,   dict()),                                   ('bm', 'int', [1], '\x03\x00\x00\x00')) +                ] +        else: +            self._Parameter_generatedata_test_data = [ +                    ((_param_A,    {'an':2, 'ambn':5,'evendist2':evendist2}), ('A', 'float*', [10, 1], b'\x08,X?M\tB?)U\xd7>\xbc\x90\x84>\xe6\xe2\x02?\x87S\xcf>\x06\xa7H?\xceK\x9b>\x84\x04\xf4>\x86X\x15?')), +                    ((_param_B,    {'ambn':5, 'bm':3,'evendist2':evendist2}), ('B', 'float*', [15, 1], b'\x16zh?(3\x01?\rM\x90>b|A?nM\x1e?^B\x80>!\xe5h?\xd4\x97{?fjO?Y\xf4f?\xaa\xcb\x9e>A\xd6:?D\x1af?\x92\x19/?\xb1\xbc\xf1>')), +                    ((_param_C,    {'an':2, 'bm':3, 'evendist2':evendist2}),  ('C', 'float*', [6, 1], b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')), +                    ((_param_ambn, {'an':2, 'bm':3}),                         ('ambn', 'int', [1], b'\x05\x00\x00\x00')), +                    ((_param_an,   dict()),                                   ('an', 'int', [1], b'\x02\x00\x00\x00')), +                    ((_param_bm,   dict()),                                   ('bm', 'int', [1], b'\x03\x00\x00\x00')) +                ] +        ### data for parsing ### +        self.parse_procedure_test_data = [ +                (('procedure void q()',), ('void', 'q', 0)), +                (('procedure int q()',), ('int', 'q', 0)), +                (('procedure float q()',), ('float', 'q', 0)), +                (('procedure unsigned int q()',), ('unsigned int', 'q', 0)), +                (('procedure void q(in int x)',), ('void', 'q', 1)), +                (('procedure void q(in int x, in int y)',), ('void', 'q', 2)), +            ] +        _mm_proc_expr = ''' +            procedure void mm( +                in  float* A    = matrix([an,ambn],evendist2), +                in  float* B    = matrix([ambn,bm],evendist2), +                out float* C    = matrix([an,bm],lambda i,j: 0), +                in  int    ambn = an + bm, +                in  int    an   = 2, +                in  int    bm   = 3) +            ''' +        self.parse_parameter_test_data = [ +                (('procedure void mm(in int x)',), [(0, 'x', 'int', 'in', False, set())]), +                (('procedure void mm(out int* x = 10)',), [(0, 'x', 'int*', 'out', True, set())]), +                ((_mm_proc_expr,),[ +                        (0, 'A', 'float*', 'in', True, set(['an','ambn','evendist2'])), +                        (1, 'B', 'float*', 'in', True, set(['ambn','bm','evendist2'])), +                        (2, 'C', 'float*', 'out', True, set(['an','bm'])), +                        (3, 'ambn', 'int', 'in', True, set(['an','bm'])), +                        (4, 'an', 'int', 'in', True, set([])), +                        (5, 'bm', 'int', 'in', True, set([])) +                    ]), +            ] +        ### data for code generation ### +        _float_2d_type = validate_env._CppArrayType(_float_type, [_name_an,_name_ambn]) +        self._CppType_statictype_test_data = [ +                ((_float_2d_type, {'an':2,'ambn':5}), 'float[2][5]') +            ] +        self._CppType_get_cdecl_stmt_test_data = [ +                ((_float_2d_type, 'A', {'an':2,'ambn':5}), 'float A[2][5];') +            ] +        self._CppType_get_cread_stmt_test_data = [ +                ((_float_2d_type, 'A', {'an':2,'ambn':5}, 'datafile_initialize', [10,1]), 'datafile_initialize.read((char*)A, 10*sizeof(float));') +            ] +        self._CppType_get_cwrite_stmt_test_data = [ +                ((_float_2d_type, 'A', {'an':2,'ambn':5}, 'datafile_out', [10,1]), 'datafile_out.write((char*)A, 10*sizeof(float));') +            ] +     +    def run_expr_test_data(self, ctor, test_data): +        for ctor_args, fv_bindings, rt_bindings, target_type, exp_freevars, exp_value in test_data: +            expr = ctor(*ctor_args) +            _expr_test(self, expr, fv_bindings, rt_bindings, target_type, exp_freevars, exp_value) +     +    def run_expr_test_data_list(self, ctor, test_data): +        for ctor_args, fv_bindings, rt_bindings, target_type, exp_freevars, exp_value in test_data: +            expr = ctor(*ctor_args) +            _expr_test_list(self, expr, fv_bindings, rt_bindings, target_type, exp_freevars, exp_value) +     +    def run_expr_test_data_invoke(self, ctor, test_data): +        for ctor_args, fv_bindings, rt_bindings, target_type, exp_freevars, invoke_args, exp_value in test_data: +            expr = ctor(*ctor_args) +            _expr_test_invoke(self, expr, fv_bindings, rt_bindings, target_type, exp_freevars, invoke_args, exp_value) +     +    def test__ConstantExpr(self): +        self.run_expr_test_data(validate_env._ConstantExpr, self._ConstantExpr_test_data) +     +    def test__NameExpr(self): +        self.run_expr_test_data(validate_env._NameExpr, self._NameExpr_test_data) +     +    def test__AttributeExpr(self): +        self.run_expr_test_data(validate_env._AttributeExpr, self._AttributeExpr_test_data) +     +    def test__UnaryExpr(self): +        self.run_expr_test_data(validate_env._UnaryExpr, self._UnaryExpr_test_data) +     +    def test__LambdaExpr(self): +        self.run_expr_test_data_invoke(validate_env._LambdaExpr, self._LambdaExpr_test_data) +     +    def test__InvokeExpr(self): +        self.run_expr_test_data(validate_env._InvokeExpr, self._InvokeExpr_test_data) +     +    def test__MatrixGenerator(self): +        self.run_expr_test_data_list(validate_env._MatrixGenerator, self._MatrixGenerator_test_data) +     +    def test__RandomExpr(self): +        random.setstate(self._RandomExpr_test_state) +        self.run_expr_test_data(validate_env._RandomExpr, self._RandomExpr_test_data) +     +    def test_parse_procedure(self): +        parse_func = testchill.cpp_validate._parse_testproc_script +        for args, expected in self.parse_procedure_test_data: +            rtype_exp, name_exp, param_count_exp = expected +            proc = parse_func(*args) +            self.assertEqual(str(proc.rtype), rtype_exp) +            self.assertEqual(proc.name, name_exp) +            self.assertEqual(len(proc.parameters), param_count_exp) +     +    def test_parse_parameter(self): +        #pylang.debug.enable(['pylang.parser.BaseTextParser.parse']) +        parse_func = testchill.cpp_validate._parse_testproc_script +        for args, expected in self.parse_parameter_test_data: +            proc = parse_func(*args) +            for param_exp in expected: +                index, name_exp, ctype_exp, direction_exp, has_init_exp, freevars_exp = param_exp +                param = proc.parameters[index] +                self.assertEqual(param.name, name_exp) +                self.assertEqual(str(param.cpptype), ctype_exp) +                self.assertEqual(param.direction, direction_exp) +                self.assertEqual(param.init_expr is not None, has_init_exp) +                self.assertEqual(param.getfreevars(), freevars_exp) +        #pylang.debug.enable(['pylang.parser.BaseTextParser.parse'], False) +     +    def test__Parameter_order_by_freevars(self): +        def testfunc(param_list): +            return [p.name for p in validate_env._Parameter.order_by_freevars(param_list)] +        for arg, expected in self._Parameter_order_by_freevars_test_data: +            self.assertEqual(testfunc(arg),expected) +     +    def test__CppType_statictype(self): +        def testfunc(ctype, glbls): +            return str(ctype.statictype(glbls)) +        for args, expected in self._CppType_statictype_test_data: +            self.assertEqual(testfunc(*args), expected) +     +    def test__CppType_formatdata(self): +        def testfunc(ctype, glbls, data): +            return ctype.statictype(glbls).formatdata(data) +        for args, expected in self._CppType_formatdata_test_data: +            dim_exp, bytes_exp = expected +            dim_val, bytes_val = testfunc(*args) +            self.assertEqual(dim_val, dim_exp) +            self.assertEqual(bytes_val, bytes_exp) +     +    def test__CppType_statictype(self): +        def testfunc(t, bindings): +            return str(t.statictype(bindings)) +        for args, typename in self._CppType_statictype_test_data: +            self.assertEqual(testfunc(*args), typename) +     +    def test__CppType_get_cdecl_stmt(self): +        def testfunc(t, param_name, bindings): +            return t.statictype(bindings).get_cdecl_stmt(param_name) +        for args, decl_exp in self._CppType_get_cdecl_stmt_test_data: +            decl_val = testfunc(*args) +            self.assertEqual(decl_val, decl_exp) +     +    def test__CppType_get_cread_stmt(self): +        def testfunc(t, param_name, bindings, stream, dims): +            return t.statictype(bindings).get_cread_stmt(param_name, stream, dims) +        for args, decl_exp in self._CppType_get_cread_stmt_test_data: +            decl_val = testfunc(*args) +            self.assertEqual(decl_val, decl_exp) +     +    def test__CppType_get_cwrite_stmt(self): +        def testfunc(t, param_name, bindings, stream, dims): +            return t.statictype(bindings).get_cwrite_stmt(param_name, stream, dims) +        for args, decl_exp in self._CppType_get_cwrite_stmt_test_data: +            decl_val = testfunc(*args) +            self.assertEqual(decl_val, decl_exp) +     +    def test__Parameter_generatedata(self): +        def testfunc(param, glbls): +            return param.generatedata(glbls) +        for args, expected in self._Parameter_generatedata_test_data: +            name_val, type_val, dims_val, data_val = testfunc(*args) +            name_exp, type_exp, dims_exp, data_exp = expected +            #print((name_val,type_val,dims_val,data_val)) +            self.assertEqual(name_val, name_exp) +            self.assertEqual(str(type_val), type_exp) +            self.assertEqual(dims_val, dims_exp) +            self.assertEqual(data_val, data_exp) +     diff --git a/test-chill/unit-tests/test__extract.py b/test-chill/unit-tests/test__extract.py new file mode 100644 index 0000000..72cba8a --- /dev/null +++ b/test-chill/unit-tests/test__extract.py @@ -0,0 +1,48 @@ +import ast +import unittest + +import testchill._extract as _extract +import testchill.util as util + +class TestExtraction(unittest.TestCase): +    def setUp(self): +        self._TagExtractor_parse_test_data = [ +                (('a',''),                      []), +                (('a','x<a>yy</a>z'),           [('yy', {})]), +                (('a','x<a>yy</a>z<a>ww</a>g'), [('yy', {}), ('ww',{})]), +                (('a','x<a>yy</a>z<b>ww</b>g'), [('yy', {})]) +            ] +        self._commented_test_data = [ +                (('no comment here','cc'), []), +                (('one comment //xxx\n','cc'), ['xxx']), +                (('two comments //xxx\nunrelated//yyy\n', 'cc'), ['xxx','yyy']), +                (('two comments //xxx\nunrelated//yyy', 'cc'), ['xxx','yyy']), +                (('ss/*x\ny\n*/z','cc'),['x\ny\n']), +                (('ss/*x\ny\n*/z//q\nc','cc'),['x\ny\n','q']), +                (('ss###x#\n','py'),['x#']), +                (('ss"""x"""\n','py'),['x']) +            ] +     +    def test__commented(self): +        def run(txt, ext): +            return list(_extract._TagExtractor._commented(txt, ext)) +        for args, res in self._commented_test_data: +            self.assertEqual(run(*args), res) +     +    #def test_extract(self): +    #    def testfunc(tag, txt): +    #        temp = util.mktemp() +    #        with open(temp, 'w') as f: +    #            f.write(txt) +    #        extracted = _extract._TagExtractor.extract_tag(tag, temp) +    #        util.rmtemp() +    #        return extracted +    #         +    #    for args, res in self.test_extract_data: +    #        self.assertEqual(testfunc(*args), res) +     +    def test__TagExtractor_parse(self): +        def testfunc(tag, txt): +            return _extract._TagExtractor._parse(tag, txt) +        for args, exp in self._TagExtractor_parse_test_data: +            self.assertEqual(testfunc(*args), exp) diff --git a/test-chill/unit-tests/test_chill.py b/test-chill/unit-tests/test_chill.py new file mode 100644 index 0000000..8aaebfe --- /dev/null +++ b/test-chill/unit-tests/test_chill.py @@ -0,0 +1,215 @@ +import logging +import os +import unittest + +import testchill.chill +import testchill.gcov +import testchill.test +import testchill.util + + +_runbuild=True + +def runtest(tclist): +    if _runbuild: +        for tc in tclist: +            tc.setUp() +            tc.setresult(tc.run()) +            tc.tearDown() + +def runchilltest(tclist, runvalidate=False, runstdout=False): +    for tc in tclist: +        tc.setUp() +        tc.compile_src(tc) +        tc.run_script(tc) +        tc.compile_gensrc(tc) +        if runvalidate: +            tc.check_run_script_validate(tc) +        if runstdout: +            tc.check_run_script_stdout(tc) +        tc.tearDown() + +class TestChillTestCases(unittest.TestCase): +    def config(self, **kwargs): +        cargs = { +                'omega_dir': self.omega_dev_dir, +                'chill_dir': self.chill_dev_dir, +                'bin_dir': self.bin_dir, +                'build_cuda': False, +                'script_lang': None, +                'version': 'dev' +            } +        cargs.update(kwargs) +        return testchill.chill.ChillConfig(**cargs) +     +    def config_rel(self, **kwargs): +        kwargs['version'] = 'release' +        kwargs['omega_dir'] = self.omega_rel_dir +        kwargs['chill_dir'] = self.chill_rel_dir +        return self.config(**kwargs) +     +    def setUp(self): +        self.chill_dev_dir = os.getenv('CHILL_DEV_SRC') +        self.chill_rel_dir = os.getenv('CHILL_RELEASE_SRC') +        self.omega_dev_dir = os.getenv('OMEGA_DEV_SRC') +        self.omega_rel_dir = os.getenv('OMEGA_RELEASE_SRC') +        self.bin_dir = os.getenv('STAGING_DIR_BIN') +        self.wd = os.getenv('STAGING_DIR_WD') +        self.build_options = {'coverage':False} +         +        testchill.util.shell('cp', [os.path.join(self.chill_dev_dir, 'examples/cuda-chill/cudaize.lua'), self.wd]) +        testchill.util.shell('cp', [os.path.join(self.chill_dev_dir, 'examples/cuda-chill/cudaize.py'), self.wd]) +         +        self.config_test_func = { +                0: lambda conf: conf.default_script_lang(), +                1: lambda conf: conf.name(), +                2: lambda conf: conf.make_depend_target(), +                3: lambda conf: conf.make_target(), +                4: lambda conf: conf.make_args() +            } +        self.config_test_data = [ +                ((self.omega_dev_dir, self.chill_dev_dir, self.bin_dir, False, None,     'dev'),     ('script', 'chill',              'depend-chill',      'chill')), +                ((self.omega_dev_dir, self.chill_dev_dir, self.bin_dir, False, 'lua',    'dev'),     ('script', 'chill-lua',          'depend-chill',      'chill')), +                ((self.omega_dev_dir, self.chill_dev_dir, self.bin_dir, False, 'python', 'dev'),     ('script', 'chill-python',       'depend-chill',      'chill')), +                ((self.omega_dev_dir, self.chill_dev_dir, self.bin_dir, True,  None,     'dev'),     ('lua',    'cuda-chill',         'depend-cuda-chill', 'cuda-chill')), +                ((self.omega_dev_dir, self.chill_dev_dir, self.bin_dir, True,  'python', 'dev'),     ('lua',    'cuda-chill-python',  'depend-cuda-chill', 'cuda-chill')), +                ((self.omega_rel_dir, self.chill_rel_dir, self.bin_dir, False, None,     'release'), ('script', 'chill-release',      'depend',            'chill')), +                ((self.omega_rel_dir, self.chill_rel_dir, self.bin_dir, True,  None,     'release'), ('lua',    'cuda-chill-release', 'depend-cuda-chill', 'cuda-chill')) +            ] +     +    def tearDown(self): +        pass +     +    def _run_ChillConfig_test(self, n): +        for args, expected in self.config_test_data: +            val = self.config_test_func[n](testchill.chill.ChillConfig(*args)) +            exp = expected[n] +            self.assertEqual(val, exp) +     +    def test_ChillConfig_default_script_lang(self): +        self._run_ChillConfig_test(0) +     +    def test_ChillConfig_name(self): +        self._run_ChillConfig_test(1) +     +    def test_ChillConfig_make_depend_target(self): +        self._run_ChillConfig_test(2) +     +    def test_ChillConfig_make_target(self): +        self._run_ChillConfig_test(3) +     +    #def test_ChillConfig_make_args(self): +    #    self._run_ChillConfig_test(4) +     +    def test_chill_dev(self): +        tc = testchill.chill.BuildChillTestCase(self.config(), self.build_options) +        self.assertEqual(tc.config.name(), 'chill') +        self.assertEqual(tc.config.env()['OMEGAHOME'], self.omega_dev_dir) +        self.assertEqual(tc.config.make_depend_target(), 'depend-chill') +        self.assertEqual(tc.config.make_target(), 'chill') +        self.assertEqual(tc.name, 'chill') +        logging.info('Building ' + tc.name) +        runtest([tc]) +     +    def test_chill_dev_lua(self): +        tc = testchill.chill.BuildChillTestCase(self.config(script_lang='lua'), self.build_options) +        self.assertEqual(tc.config.name(), 'chill-lua') +        self.assertEqual(tc.config.env()['OMEGAHOME'], self.omega_dev_dir) +        self.assertEqual(tc.config.make_depend_target(), 'depend-chill') +        self.assertEqual(tc.config.make_target(), 'chill') +        self.assertEqual(tc.config.make_args(), 'SCRIPT_LANG=lua') +        self.assertEqual(tc.name, 'chill-lua') +        logging.info('Building ' + tc.name) +        runtest([tc]) +     +    def test_chill_dev_python(self): +        tc = testchill.chill.BuildChillTestCase(self.config(script_lang='python'), self.build_options) +        self.assertEqual(tc.config.name(), 'chill-python') +        self.assertEqual(tc.config.env()['OMEGAHOME'], self.omega_dev_dir) +        self.assertEqual(tc.config.make_depend_target(), 'depend-chill') +        self.assertEqual(tc.config.make_target(), 'chill') +        self.assertEqual(tc.config.make_args(), 'SCRIPT_LANG=python') +        self.assertEqual(tc.name, 'chill-python') +        logging.info('Building ' + tc.name) +        runtest([tc]) +     +    def test_cudachill_dev(self): +        tc = testchill.chill.BuildChillTestCase(self.config(build_cuda=True), self.build_options) +        self.assertEqual(tc.config.name(), 'cuda-chill') +        self.assertEqual(tc.config.env()['OMEGAHOME'], self.omega_dev_dir) +        self.assertEqual(tc.config.make_depend_target(), 'depend-cuda-chill') +        self.assertEqual(tc.config.make_target(), 'cuda-chill') +        self.assertEqual(tc.name, 'cuda-chill') +        logging.info('Building ' + tc.name) +        runtest([tc]) +     +    def test_cudachill_dev(self): +        tc = testchill.chill.BuildChillTestCase(self.config(build_cuda=True, script_lang='python'), self.build_options) +        self.assertEqual(tc.config.name(), 'cuda-chill-python') +        self.assertEqual(tc.config.env()['OMEGAHOME'], self.omega_dev_dir) +        self.assertEqual(tc.config.make_depend_target(), 'depend-cuda-chill') +        self.assertEqual(tc.config.make_target(), 'cuda-chill') +        self.assertEqual(tc.name, 'cuda-chill-python') +        logging.info('Building ' + tc.name) +        runtest([tc]) + +    def test_chill_release(self): +        tc = testchill.chill.BuildChillTestCase(self.config_rel(), self.build_options) +        self.assertEqual(tc.config.name(), 'chill-release') +        self.assertEqual(tc.config.env()['OMEGAHOME'], self.omega_rel_dir) +        self.assertEqual(tc.config.make_depend_target(), 'depend') +        self.assertEqual(tc.config.make_target(), 'chill') +        self.assertEqual(tc.name, 'chill-release') +        logging.info('Building ' + tc.name) +        runtest([tc]) +     +    def test_cudachill_release(self): +        tc = testchill.chill.BuildChillTestCase(self.config_rel(build_cuda=True), self.build_options) +        self.assertEqual(tc.config.name(), 'cuda-chill-release') +        self.assertEqual(tc.config.env()['OMEGAHOME'], self.omega_rel_dir) +        self.assertEqual(tc.config.env()['CUDACHILL'], 'true') +        self.assertEqual(tc.config.make_depend_target(), 'depend-cuda-chill') +        self.assertEqual(tc.config.make_target(), 'cuda-chill') +        self.assertEqual(tc.name, 'cuda-chill-release') +        logging.info('Building ' + tc.name) +        runtest([tc]) +     +    def test_run_chill(self): +        config = self.config() +        btc = testchill.chill.BuildChillTestCase(config, self.build_options) +        runtest([btc]) +        tc = testchill.chill.RunChillTestCase(config, 'test-cases/chill/test_scale.script', 'test-cases/chill/mm.c', wd=self.wd) +        self.assertEqual(tc.chill_src, 'mm.c') +        self.assertEqual(tc.chill_script, 'test_scale.script') +        self.assertEqual(tc.chill_src_path, os.path.join(os.getcwd(), 'test-cases/chill/mm.c')) +        self.assertEqual(tc.chill_script_path, os.path.join(os.getcwd(), 'test-cases/chill/test_scale.script')) +        self.assertEqual(tc.chill_gensrc, 'rose_mm.c') +        self.assertEqual(tc.name, 'chill:test_scale.script') +        runchilltest([tc]) +     +    def test_run_cudachill(self): +        config = self.config(build_cuda=True) +        btc = testchill.chill.BuildChillTestCase(config, self.build_options) +        runtest([btc]) +        tc = testchill.chill.RunChillTestCase(config, 'test-cases/examples/cuda-chill/mm.lua', 'test-cases/examples/cuda-chill/mm.c', wd=self.wd) +        self.assertEqual(tc.chill_src, 'mm.c') +        self.assertEqual(tc.chill_script, 'mm.lua') +        self.assertEqual(tc.chill_src_path, os.path.join(os.getcwd(), 'test-cases/examples/cuda-chill/mm.c')) +        self.assertEqual(tc.chill_script_path, os.path.join(os.getcwd(), 'test-cases/examples/cuda-chill/mm.lua')) +        self.assertEqual(tc.chill_gensrc, 'rose_mm.cu') +        self.assertEqual(tc.name, 'cuda-chill:mm.lua') +        runchilltest([tc]) +     +    def test_chill_coverage(self): +        tc = testchill.chill.BuildChillTestCase(self.config(), options={'coverage':True}, coverage_set=testchill.gcov.GcovSet()) +        self.assertEqual(tc.config.name(), 'chill') +        self.assertEqual(tc.config.env()['OMEGAHOME'], self.omega_dev_dir) +        self.assertEqual(tc.config.make_depend_target(), 'depend-chill') +        self.assertEqual(tc.config.make_target(), 'chill') +        self.assertEqual(tc.name, 'chill') +        self.assertTrue(tc.options['coverage']) +        logging.info('Building ' + tc.name) +        if _runbuild: +            runtest([tc]) +            self.assertTrue(os.path.exists(os.path.join(self.chill_dev_dir, 'ir_rose.gcno'))) + diff --git a/test-chill/unit-tests/test_cpp_validate.py b/test-chill/unit-tests/test_cpp_validate.py new file mode 100644 index 0000000..ed55c80 --- /dev/null +++ b/test-chill/unit-tests/test_cpp_validate.py @@ -0,0 +1,280 @@ +import functools +import os +import pprint +import struct +import unittest + +import testchill +import testchill.util as util +import testchill._cpp_validate_env as cpp_validate_env +import testchill.cpp_validate as cpp_validate + + +def listtodata(flist): +    data = [struct.pack('f',n) for n in flist] +    return functools.reduce(lambda a,v: a+v, data) + +class TestCppValidate(unittest.TestCase): +    def setUp(self): +        self.staging_dir_wd = os.getenv("STAGING_DIR_WD") +        self.cpp_validate_dir = os.path.join(os.getcwd(),'unit-tests/cpp_validate_prog/') +        self._parse_testproc_script_test_data = [ +                (('mm_one.testproc',),      None), +                (('mm_one_with.testproc',), None) +            ] +        self._parse_testproc_python_test_data = [ +            ] +        #self._generate_data_test_data = [ +        #        (('mm_one.cc','in'),               None), +        #        (('mm_one.cc','out'),              None), +        #        (('mm_one_with.cc','in'),          None), +        #        (('mm_one_with.cc','out'),         None), +        #        (('mm_one_defines.cc','in'),       None), +        #        (('mm_one_defines.cc','out'),      None), +        #        (('mm_one_with_defines.cc','in'),  None), +        #        (('mm_one_with_defines.cc','out'), None), +        #    ] +        self._parse_testproc_iter_test_data = [ +                (('mm_one.cc',), +                    [({'lang': 'script', 'name': 'mm_small', 'define':'dict()'},)]), +                (('mm_one_with.cc',), +                    [({'lang': 'script', 'name': 'mm_small', 'define':'dict()'},)]), +                (('mm_one_defines.cc',), +                    [({'lang': 'script', 'name': 'mm_small', 'define': "{'AN':3, 'BM':2, 'AMBN':5}"},)]), +                (('mm_one_with_defines.cc',), +                    [({'lang': 'script', 'name': 'mm_small', 'define': "{'AN':3, 'BM':2, 'AMBN':5}"},)]) +            ] +        self._compile_gpp_test_data = [ +                ('mm_one_main.cc', 'mm_one') +            ] +        self._test_time_test_data = [ +                ((0.0034, 0.0025), True), +                ((0.0025, 0.0034), False) +            ] +        self._test_validate_test_data = [ +                (('asdf', 'asdf'), True), +                (('asdf', 'sdfg'), False) +            ] +        self._run_test_validate_time_test_data = [ +                (('mm_one_main.cc', 'mm_control', 'mm_one_longer_main.cc', 'mm_test', list(range(15)) + list(range(10))), (True, False)), +                (('mm_one_longer_main.cc', 'mm_control', 'mm_one_main.cc', 'mm_test', list(range(15)) + list(range(10))), (True, True)), +                (('mm_one_main.cc', 'mm_control', 'mm_one_longer_wrong_main.cc', 'mm_test', list(range(15)) + list(range(10))), (False, False)) +            ] +        self._compile_run_test_validate_time_test_data = [ +                (('mm_one_main.cc', 'mm_one_longer_main.cc', list(range(15)) + list(range(10))), (True, False)), +                (('mm_one_longer_main.cc', 'mm_one_main.cc', list(range(15)) + list(range(10))), (True, True)), +                (('mm_one_main.cc', 'mm_one_longer_wrong_main.cc', list(range(15)) + list(range(10))), (False, False)) +            ] +        self._generate_initial_data_test_data = [ +                (('mm_one.testproc', 'mm.cc', {}),      listtodata(list(range(15)) + list(range(10)) + [0]*6)), +                (('mm_one_with.testproc', 'mm.cc', {}), listtodata(list(range(15)) + list(range(10)) + [0]*6)), +            ] +        self._format_insertion_dict_test_data = [ +                (('mm_one.testproc', 'mm_one.cc', {}), +                    { +                        'run': 'mm(A,B,C);', +                        'read-out': 'datafile_initialize.read((char*)C, 6*sizeof(float));', +                        'declarations': 'float A[3][5];\nfloat B[5][2];\nfloat C[3][2];', +                        'write-out': 'datafile_out.write((char*)C, 6*sizeof(float));', +                        'defines': '', +                        'read-in': 'datafile_initialize.read((char*)A, 15*sizeof(float));\ndatafile_initialize.read((char*)B, 10*sizeof(float));' +                    }), +                (('mm_one_with.testproc', 'mm_one.cc', {}), +                    { +                        'run': 'mm(A,B,C);', +                        'read-out': 'datafile_initialize.read((char*)C, 6*sizeof(float));', +                        'declarations': 'float A[3][5];\nfloat B[5][2];\nfloat C[3][2];', +                        'write-out': 'datafile_out.write((char*)C, 6*sizeof(float));', +                        'defines': '', +                        'read-in': 'datafile_initialize.read((char*)A, 15*sizeof(float));\ndatafile_initialize.read((char*)B, 10*sizeof(float));' +                    }), +            ] +        self._write_generated_code_test_data = [ +                (('mm_one.testproc', 'mm_one.cc', 'control.cc', {}), 'mm_one_out.cc') +            ] +        self.run_from_src_test_data = [ +                (('mm_three_basic.cc', 'mm_three_slow.cc', self.staging_dir_wd), [('small', (True, False)), ('medium', (True, False)), ('big', (True, False))]), +                (('mm_three_slow.cc', 'mm_three_basic.cc', self.staging_dir_wd), [('small', (True, True)), ('medium', (True, True)), ('big', (True, True))]), +            ] +     +    def tearDown(self): +        util.rmtemp() +     +    def test__get_script_parser(self): +        cpp_validate._script_parser = None +        self.assertIsNotNone(cpp_validate._get_script_parser()) +        self.assertIsNotNone(cpp_validate._get_script_parser()) +     +    def _test_parse_src(self, parsefunc, test_data): +        def parse_file(filename): +            path = os.path.join(self.cpp_validate_dir, filename) +            with open(path, 'r') as f: +                src = f.read() +            return parsefunc(src) +        for args, expected in test_data: +            srcfile, = args +            val = parse_file(srcfile) +            #TODO: make some assertions +     +    def test__parse_testproc_script(self): +        self._test_parse_src( +                cpp_validate._parse_testproc_script, +                self._parse_testproc_script_test_data) +     +    @unittest.skip("not yet supported") +    def test__parse_testproc_python(self): +        self._test_parse_src( +                cpp_validate._parse_testproc_python, +                self._parse_testproc_python_test_data) +     +    def test__parse_testproc_iter(self): +        def testfunc(filename): +            path = os.path.join(self.cpp_validate_dir, filename) +            util.shell('cp', [path, '.'], wd=self.staging_dir_wd) +            return list(cpp_validate._parse_testproc_iter(filename, wd=self.staging_dir_wd)) +        for args, expected_list in self._parse_testproc_iter_test_data: +            val_list = testfunc(*args) +            for val, expected in zip(val_list, expected_list): +                _, attr_val = val +                attr_exp, = expected +                self.assertEqual(attr_val, attr_exp) +            #TODO: make some more assertions +     +    #def test__generate_data(self): +    #    def testfunc(filename, direction): +    #        path = os.path.join(self.cpp_validate_dir, filename) +    #        util.shell('cp', [path, '.'], wd=self.staging_dir_wd) +    #        for proc, attrs in cpp_validate._parse_testproc_iter(filename, wd=self.staging_dir_wd): +    #            defines = eval(attrs['define']) +    #            yield cpp_validate._generate_initial_data(proc, direction, filename, defines, wd=self.staging_dir_wd) +    #         +    #    for args, expected in self._generate_data_test_data: +    #        for filename in testfunc(*args): +    #            self.assertTrue(os.path.exists(filename)) +    #        #TODO: make some more assertions +     +    def test__compile_gpp(self): +        def testfunc(src, obj): +            src = os.path.join(self.cpp_validate_dir, src) +            obj = os.path.join(self.staging_dir_wd, obj) +            cpp_validate._compile_gpp(src, obj) +         +        for src, obj in self._compile_gpp_test_data: +            testfunc(src, obj) +            obj_path = os.path.join(self.staging_dir_wd, obj) +            self.assertTrue(os.path.exists(obj_path)) +     +    def test__test_time(self): +        def testfunc(control_time, test_time): +            return cpp_validate._test_time(control_time, test_time) +         +        for args, exp in self._test_time_test_data: +            val = testfunc(*args) +            self.assertEqual(val, exp) +     +    def test__test_validate(self): +        def testfunc(control_data, test_data): +            if util.python_version_major == 3: +                control_data = bytes(map(ord,control_data)) +                test_data = bytes(map(ord,test_data)) +            control_file, control_path = util.mktemp('wb') +            control_file.write(control_data) +            control_file.close() +            test_file, test_path = util.mktemp('wb') +            test_file.write(test_data) +            test_file.close() +            return cpp_validate._test_validate(control_path, test_path) +         +        for args, exp in self._test_validate_test_data: +            val = testfunc(*args) +            self.assertEqual(val, exp) +     +    def test__run_test_validate_time(self): +        def makeobj(src, obj): +            src_path = os.path.join(self.cpp_validate_dir, src) +            obj_path = os.path.join(self.staging_dir_wd, obj) +            util.shell('g++', ['-o', obj_path, src_path, '-lrt']) +            util.set_tempfile(obj_path) +            return src_path, obj_path +         +        def testfunc(control_src, control_obj, test_src, test_obj, in_data): +            control_src, control_obj = makeobj(control_src, control_obj) +            test_src, test_obj = makeobj(test_src, test_obj) +            inpath = os.path.join(self.staging_dir_wd, 'test.in.data') +            with open(inpath, 'wb') as infile: +                infile.write(listtodata(in_data)) +            util.set_tempfile(inpath) +            return cpp_validate._run_test_validate_time(control_obj, test_obj, inpath) +         +        for args, expected in self._run_test_validate_time_test_data: +            validate_val, time_val = testfunc(*args) +            validate_exp, time_exp = expected +            self.assertEqual(validate_val, validate_exp) +            self.assertEqual(time_val, time_exp) +     +    def test__compile_run_test_validate_time(self): +        def testfunc(control_src, test_src, in_data): +            control_src = os.path.join(self.cpp_validate_dir, control_src) +            test_src = os.path.join(self.cpp_validate_dir, test_src) +            inpath = os.path.join(self.staging_dir_wd, 'test.in.data') +            with open(inpath, 'wb') as infile: +                infile.write(listtodata(in_data)) +            util.set_tempfile(inpath) +            return cpp_validate._compile_run_test_validate_time(control_src, test_src, inpath) +         +        for args, expected in self._compile_run_test_validate_time_test_data: +            validate_val, time_val = testfunc(*args) +            validate_exp, time_exp = expected +            self.assertEqual(validate_val, validate_exp) +            self.assertEqual(time_val, time_exp) +     +    def test__generate_initial_data(self): +        def testfunc(testprocfile, srcfile, defines): +            testprocpath = os.path.join(self.cpp_validate_dir, testprocfile) +            with open(testprocpath, 'r') as f: +                srcpath = os.path.join(self.cpp_validate_dir, srcfile) +                testproc = cpp_validate._parse_testproc_script(f.read()) +                return cpp_validate._generate_initial_data(testproc, srcpath, defines, wd=self.staging_dir_wd) +         +        for args, expected in self._generate_initial_data_test_data: +            datafile = testfunc(*args) +            with open(datafile, 'rb') as f: +                self.assertEqual(len(f.read()), len(expected)) +     +    def test__format_insertion_dict(self): +        def testfunc(testprocfile, srcfile, defines): +            testprocpath = os.path.join(self.cpp_validate_dir, testprocfile) +            srcpath = os.path.join(self.cpp_validate_dir, srcfile) +            with open(testprocpath, 'r') as f: +                testproc = cpp_validate._parse_testproc_script(f.read()) +                #testproc.generatedata('in', defines) +                #testproc.generatedata('out', defines) +            return cpp_validate._format_insertion_dict(testproc, srcpath, defines) +                 +        for args, exp in self._format_insertion_dict_test_data: +            val = testfunc(*args) +            for k,v in exp.items(): +                self.assertEqual(val[k], v) +     +    def test__write_generated_code(self): +        def testfunc(testprocfile, srcname, destname, defines): +            srcpath = os.path.join(self.cpp_validate_dir, srcname) +            with open(os.path.join(self.cpp_validate_dir, testprocfile),'r') as f: +                testproc = cpp_validate._parse_testproc_script(f.read()) +            return cpp_validate._write_generated_code(testproc, srcpath, defines, destname, self.staging_dir_wd) +        for args, exp_path in self._write_generated_code_test_data: +            val_path = testfunc(*args) +            util.set_tempfile(val_path) +            exp_path = os.path.join(self.cpp_validate_dir, exp_path) +            with open(val_path, 'r') as valfile: +                with open(exp_path, 'r') as expfile: +                    self.assertEqual(valfile.read().splitlines(), expfile.read().splitlines()) +     +    def test_run_from_src(self): +        for args, expected in self.run_from_src_test_data: +            control_src, test_src, wd = args +            control_src = os.path.join(self.cpp_validate_dir, control_src) +            test_src = os.path.join(self.cpp_validate_dir, test_src) +            val = list(cpp_validate.run_from_src(control_src,test_src,wd)) +            self.assertEqual(val, expected) +             diff --git a/test-chill/unit-tests/test_gcov.py b/test-chill/unit-tests/test_gcov.py new file mode 100644 index 0000000..2720ef7 --- /dev/null +++ b/test-chill/unit-tests/test_gcov.py @@ -0,0 +1,98 @@ +import itertools +import pprint +import os +import textwrap +import unittest + +import testchill.util as util +import testchill.gcov as gcov + + +class TestGCov(unittest.TestCase): +    def setUp(self): +        self.cprog_dir = os.path.join(os.getcwd(), 'unit-tests/cprog') +        self.cprog_bin = os.path.join(self.cprog_dir, 'bin/sorter') +     +    def build_prog(self): +        self.clean_prog() +        util.shell('make', [], wd=self.cprog_dir) +     +    def clean_prog(self): +        util.shell('make', ['clean'], wd=self.cprog_dir) +     +    def run_prog(self, alg, lst): +        util.shell(self.cprog_bin, [alg] + list(map(str,lst))) +     +    def test_GcovLine_mrege_lines(self): +        ''' +           56:   14:        while((index < pivot_index) && (list[index] >= pivot_value)) { +            6:   15:            swap(list, index, pivot_index); +            6:   16:            pivot_index--; +            -:   17:        } +        And +            78:   14:        while((index < pivot_index) && (list[index] >= pivot_value)) { +            18:   15:            swap(list, index, pivot_index); +            18:   16:            pivot_index--; +            -:   17:        } +        ''' +        lines_proc_one = list(itertools.starmap(gcov.GcovLine,[  +                (14, {'proc_one':   56},'        while((index < pivot_index) && (list[index] >= pivot_value)) {'), +                (15, {'proc_one':    6},'            swap(list, index, pivot_index);'), +                (16, {'proc_one':    6},'            pivot_index--;'), +                (17, {'proc_one': None},'        }')])) +        lines_proc_two = list(itertools.starmap(gcov.GcovLine,[ +                (14, {'proc_two':   78},'        while((index < pivot_index) && (list[index] >= pivot_value)) {'), +                (15, {'proc_two':   18},'            swap(list, index, pivot_index);'), +                (16, {'proc_two':   18},'            pivot_index--;'), +                (17, {'proc_two': None},'        }')])) +        gcov.GcovLine.merge_lines(lines_proc_one, lines_proc_two) +        self.assertEqual(lines_proc_one[0].lineno, 14) +        self.assertEqual(lines_proc_one[1].lineno, 15) +        self.assertEqual(lines_proc_one[2].lineno, 16) +        self.assertEqual(lines_proc_one[3].lineno, 17) +     +    def test_GcovLine_merge_and_count(self): +        lines_proc_one = list(itertools.starmap(gcov.GcovLine,[  +                (14, {'proc_one':   56},'        while((index < pivot_index) && (list[index] >= pivot_value)) {'), +                (15, {'proc_one':    6},'            swap(list, index, pivot_index);'), +                (16, {'proc_one':    6},'            pivot_index--;'), +                (17, {'proc_one': None},'        }')])) +        lines_proc_two = list(itertools.starmap(gcov.GcovLine,[ +                (14, {'proc_two':   78},'        while((index < pivot_index) && (list[index] >= pivot_value)) {'), +                (15, {'proc_two':   18},'            swap(list, index, pivot_index);'), +                (16, {'proc_two':   18},'            pivot_index--;'), +                (17, {'proc_two': None},'        }')])) +        gcov.GcovLine.merge_lines(lines_proc_one, lines_proc_two) +        self.assertEqual(lines_proc_one[0].count(), 134) +        self.assertEqual(lines_proc_one[1].count(), 24) +        self.assertEqual(lines_proc_one[2].count(), 24) +        self.assertEqual(lines_proc_one[3].count(), None) +     +    def test_GcovFile_parse_lines(self): +        lines = textwrap.dedent( +            '''-:0:SomeProperty:SomeValue +               56:   14:        while((index < pivot_index) && (list[index] >= pivot_value)) { +                6:   15:            swap(list, index, pivot_index); +                6:   16:            pivot_index--; +                -:   17:        }''').splitlines() +        lines, properties = gcov.GcovFile.parse_lines(lines, 'proc') +        self.assertEqual(lines[0].lineno, 14) +        self.assertEqual(lines[0].count_by_process, {'proc': 56}) +        self.assertEqual(lines[0].code, '        while((index < pivot_index) && (list[index] >= pivot_value)) {') +        self.assertEqual(lines[3].count_by_process, dict()) +     +    def test_Gcov_parse(self): +        self.build_prog() +        self.run_prog('quicksort', [9, 4, 10, 6, 11, 0, 3, 7, 2, 1, 8, 5]) +        cov = gcov.Gcov.parse(self.cprog_dir, 'unsorted') +        self.build_prog() +        self.run_prog('quicksort', [5, 4, 3, 2, 1]) +        #pprint.pprint(vars(cov.files['QuickSorter.cc'])) +        cov.merge(gcov.Gcov.parse(self.cprog_dir, 'reverse')) +        #pprint.pprint(vars(cov.files['QuickSorter.cc'])) +        #TODO: assert something +        #cov.pretty_print() +     +    def tearDown(self): +        self.clean_prog() +         diff --git a/test-chill/unit-tests/test_omega.py b/test-chill/unit-tests/test_omega.py new file mode 100644 index 0000000..91d6a13 --- /dev/null +++ b/test-chill/unit-tests/test_omega.py @@ -0,0 +1,23 @@ +import os +import unittest + +import testchill.omega +import testchill.util + + +class TestOmegaTestCases(unittest.TestCase): +    def setUp(self): +        self.omega_dev_dir = os.getenv('OMEGA_DEV_SRC') +        self.omega_rel_dir = os.getenv('OMEGA_RELEASE_SRC') +     +    def tearDown(self): +        pass +     +    def test_omega_dev(self): +        tc = testchill.omega.BuildOmegaTestCase(self.omega_dev_dir) +        tc.run() +         +    def test_omega_release(self): +        tc = testchill.omega.BuildOmegaTestCase(self.omega_rel_dir, 'release') +        tc.run() +     diff --git a/test-chill/unit-tests/test_test.py b/test-chill/unit-tests/test_test.py new file mode 100644 index 0000000..9745358 --- /dev/null +++ b/test-chill/unit-tests/test_test.py @@ -0,0 +1,380 @@ +import io +import pickle +import pprint +import unittest +import textwrap + +import testchill.test as test +import testchill.util as util + + +class Named(object): +    def __init__(self, name): +        self.name = name +     +    def setresult(self, res): +        pass + +def make_tc(rfunc=None, sufunc=None, tdfunc=None, name=None): +    class SomeTestCase(test.TestCase): +        def setUp(self): +            if sufunc: +                sufunc(self) +             +        def run(self): +            if rfunc != None: +                return rfunc(self) +             +        def tearDown(self): +            if tdfunc: +                tdfunc(self) +     +    return SomeTestCase(name) + +def make_seqtc(subtests, sufunc=None, tdfunc=None, name=None): +    class SomeSeqTestCase(test.SequencialTestCase): +        def __init__(self, name): +            test.SequencialTestCase.__init__(self, name) +            for fn_name, func in subtests: +                self.add_subtest(fn_name, func) +         +        def setUp(self): +            if sufunc: +                sufunc(self) +                 +        def tearDown(self): +            if tdfunc: +                tdfunc(self) +         +    return SomeSeqTestCase(name) + + +class TestTest(unittest.TestCase): +     +    def flip_n_switch(self, n, value=True): +        ''' +        Return a function that sets switches[n] to value (True by default) +        ''' +        def flipswitch(tc): +            self.switches[n] = value +        return flipswitch +     +    def flip_n_switch_if_m(self, n, m, value=True): +        ''' +        Returns a function that sets switches[n] to value (True by default) if switches[m] is True +        ''' +        def flipswitch(tc): +            if self.switches[m]: +                self.switches[n] = value +        return flipswitch +     +    def allways_raise(self, exc=Exception('Expected exception')): +        ''' +        Returns a function that raises an exception +        ''' +        def throwexc(tc): +            raise exc +        return throwexc +     +    def allways_fail(self): +        ''' +        Returns a function that returns an explicit failure +        ''' +        def fail(tc): +            return test.TestResult.make_fail(test.TestResult, tc) +        return fail +     +    def allways_skip(self): +        ''' +        Returns a function that skips +        ''' +        def skip(tc): +            return test.TestResult.make_skipped(test.TestResult, tc) +        return skip +     +    def allways_pass(self): +        ''' +        Returns a function that passes +        ''' +        def notfail(tc): +            return test.TestResult.make_pass(test.TestResult, tc) +        return notfail +     +    def donothing(self): +        ''' +        Returns a function that does nothing +        ''' +        def foo(tc): +            pass +        return foo +     +    def setUp(self): +        self.switches = dict((n, False) for n in range(3)) +     +    def test_TestResult_make_pass(self): +        self.assertTrue(test.TestResult.make_pass(test.TestResult, Named('i-pass')).passed()) +        self.assertFalse(test.TestResult.make_pass(test.TestResult, Named('i-pass')).errored()) +        self.assertFalse(test.TestResult.make_pass(test.TestResult, Named('i-pass')).failed()) +        self.assertFalse(test.TestResult.make_pass(test.TestResult, Named('i-pass')).skipped()) +     +    def test_TestResult_make_error(self): +        self.assertFalse(test.TestResult.make_error(test.TestResult, Named('i-error')).passed()) +        self.assertTrue(test.TestResult.make_error(test.TestResult, Named('i-error')).errored()) +        self.assertFalse(test.TestResult.make_error(test.TestResult, Named('i-error')).failed()) +        self.assertFalse(test.TestResult.make_error(test.TestResult, Named('i-error')).skipped()) +     +    def test_TestResult_make_fail(self): +        self.assertFalse(test.TestResult.make_fail(test.TestResult, Named('i-fail')).passed()) +        self.assertFalse(test.TestResult.make_fail(test.TestResult, Named('i-fail')).errored()) +        self.assertTrue(test.TestResult.make_fail(test.TestResult, Named('i-fail')).failed()) +        self.assertFalse(test.TestResult.make_fail(test.TestResult, Named('i-fail')).skipped()) +     +    def test_TestResult_make_skipped(self): +        self.assertFalse(test.TestResult.make_skipped(test.TestResult, Named('i-skip')).passed()) +        self.assertFalse(test.TestResult.make_skipped(test.TestResult, Named('i-skip')).errored()) +        self.assertFalse(test.TestResult.make_skipped(test.TestResult, Named('i-skip')).failed()) +        self.assertTrue(test.TestResult.make_skipped(test.TestResult, Named('i-skip')).skipped()) +     +    def test__result(self): +        result_passed = test.TestResult.make_pass(test.TestResult, Named('i-pass')) +        result_failed = test.TestResult.make_fail(test.TestResult, Named('i-fail')) +        self.assertTrue(result_passed is test._result(result_passed, Named('i-pass'))) +        self.assertTrue(test._result(result_failed, Named('i-fail')).failed()) +        self.assertTrue(test._result(Exception(), Named('i-error')).errored()) +     +    def test_run_empty(self): +        test.run([]) +     +    def test_run_run(self): +        test.run([make_tc( +            rfunc=self.flip_n_switch(0))]) +        self.assertTrue(self.switches[0]) +     +    def test_run_setupfirst(self): +        test.run([make_tc( +                rfunc = self.flip_n_switch_if_m(0,1), +                sufunc = self.flip_n_switch(1))]) +        self.assertTrue(self.switches[0]) +     +    def test_run_teardownlast(self): +        test.run([make_tc( +                rfunc = self.flip_n_switch(1), +                tdfunc = self.flip_n_switch_if_m(0,1))]) +        self.assertTrue(self.switches[0]) +     +    def test_run_teardown_allways(self): +        test.run([make_tc( +                rfunc = self.allways_raise(), +                tdfunc = self.flip_n_switch(0))]) +        self.assertTrue(self.switches[0]) +     +    def test_run_pass_result(self): +        result_set = test.run([make_tc( +                rfunc = self.donothing(), +                name='pass')]) +        result = result_set[0] +        self.assertTrue(result.passed()) +        self.assertFalse(result.errored()) +        self.assertFalse(result.failed()) +        self.assertFalse(result.skipped()) +     +    def test_run_error_result(self): +        result_set = test.run([make_tc( +                rfunc = self.allways_raise(), +                name='error')]) +        result = result_set[0] +        self.assertFalse(result.passed()) +        self.assertTrue(result.errored()) +        self.assertFalse(result.failed()) +        self.assertFalse(result.skipped()) +     +    def test_run_fail_result(self): +        result_set = test.run([make_tc( +                rfunc = self.allways_fail(), +                name='fail')]) +        result = result_set[0] +        self.assertFalse(result.passed()) +        self.assertFalse(result.errored()) +        self.assertTrue(result.failed()) +        self.assertFalse(result.skipped()) + +    def test_run_skipped_result(self): +        result_set = test.run([make_tc( +                rfunc = self.allways_skip(), +                name='skipped')]) +        result = result_set[0] +        self.assertFalse(result.passed()) +        self.assertFalse(result.errored()) +        self.assertFalse(result.failed()) +        self.assertTrue(result.skipped()) +     +    def test_run_seq_empty(self): +        test.run([make_seqtc([])]) +     +    def test_run_seq_allrun(self): +        result_set = test.run([make_seqtc([ +                ('one', self.flip_n_switch(0)), +                ('two', self.flip_n_switch(1)), +                ('three', self.flip_n_switch(2))], +                name='seq')]) +        self.assertTrue(result_set[0].passed()) +        self.assertTrue(self.switches[0]) +        self.assertTrue(self.switches[1]) +        self.assertTrue(self.switches[2]) +     +    def test_run_seq_until_fail(self): +        result_set = test.run([make_seqtc([ +                ('one', self.flip_n_switch(0)), +                ('two', self.allways_fail()), +                ('trhee', self.flip_n_switch(1))], +                name='seq')]) +        self.assertTrue(result_set[0].failed()) +        self.assertTrue(self.switches[0]) +        self.assertFalse(self.switches[1]) +     +    def test_run_seq_until_error(self): +        result_set = test.run([make_seqtc([ +                ('one', self.flip_n_switch(0)), +                ('two', self.allways_raise()), +                ('trhee', self.flip_n_switch(1))], +                name='seq')]) +        self.assertTrue(result_set[0].errored()) +        self.assertTrue(self.switches[0]) +        self.assertFalse(self.switches[1]) +     +    def test_persistance_one_pass(self): +        result_set = test.run([make_tc(self.allways_pass(), name='tc-name')]) +        read_result_set = util.withtmp( +            lambda f: pickle.dump(result_set, f), +            lambda f: pickle.load(f)) +        self.assertEqual(list(map(vars,result_set)), list(map(vars,read_result_set))) +     +    def test_persistance_seq(self): +        result_set = test.run([make_seqtc([ +            ('one', self.flip_n_switch(0)), +            ('two', self.flip_n_switch(1))], +            name = 'seq')]) +        read_result_set = util.withtmp( +            lambda f: pickle.dump(result_set, f), +            lambda f: pickle.load(f)) +         +        for i in range(len(result_set)): +            self.assertEqual(result_set[i].status, read_result_set[i].status) +            self.assertEqual(result_set[i].testcase_name, read_result_set[i].testcase_name) +            for j in range(len(result_set[i].sub_results)): +                self.assertEqual(result_set[i].sub_results[j].status, read_result_set[i].sub_results[j].status) +                self.assertEqual(result_set[i].sub_results[j].testcase_name, read_result_set[i].sub_results[j].testcase_name) +     +    def test_persistance_seq_error(self): +        result_set = test.run([make_seqtc([ +            ('one', self.flip_n_switch(0)), +            ('two', self.allways_raise())], +            name = 'seq')]) +        read_result_set = util.withtmp( +            lambda f: pickle.dump(result_set, f), +            lambda f: pickle.load(f)) +         +        for i in range(len(result_set)): +            self.assertEqual(result_set[i].status, read_result_set[i].status) +            self.assertEqual(result_set[i].testcase_name, read_result_set[i].testcase_name) +            for j in range(len(result_set[i].sub_results)): +                self.assertEqual(result_set[i].sub_results[j].status, read_result_set[i].sub_results[j].status) +                self.assertEqual(result_set[i].sub_results[j].testcase_name, read_result_set[i].sub_results[j].testcase_name) +         +    def test_FailedTestResult_init(self): +        result = test.TestResult.make_fail(test.FailedTestResult, Named('i-fail'), reason='testing') +        self.assertFalse(result.passed()) +        self.assertTrue(result.failed()) +        self.assertFalse(result.errored()) +        self.assertFalse(result.skipped()) +        self.assertEqual(result.testcase_name, 'i-fail') +        self.assertEqual(result.reason, 'testing') +     +    def test_pretty_print(self): +        def pretty_print_to_string(results_iter): +            sio = util.StringIO() +            test.pretty_print_results(results_iter, outfile=sio) +            return sio.getvalue() +             +        results_iter = iter([ +                test.TestResult.make_pass(test.TestResult, Named('i-pass')), +                test.TestResult.make_error(test.UnhandledExceptionTestResult, Named('i-error'), Exception, Exception(), None), +                test.TestResult.make_fail(test.FailedTestResult, Named('i-fail'), reason='Oops'), +                test.TestResult.make_skipped(test.TestResult, Named('i-skip')) +            ]) +         +        self.assertEqual(pretty_print_to_string(results_iter), textwrap.dedent('''\ +            Passed: 1 +            Errors: 1 +            Failed: 1 +            Skipped: 1 +            ============================================================ +            error: i-error +            ------------------------------------------------------------ +            <class 'Exception'>:  +            ------------------------------------------------------------ +            ============================================================ +            fail: i-fail +            ------------------------------------------------------------ +            Oops +            ------------------------------------------------------------ +            ''')) +        result_set = test.run([make_seqtc([ +                ('one', self.flip_n_switch(0)), +                ('two', self.flip_n_switch(1)), +                ('three', self.flip_n_switch(2))], +                name='seq')]) +        result_set_fail = test.run([make_seqtc([ +                ('one', self.flip_n_switch(0)), +                ('two', lambda s: test.TestResult.make_fail(test.FailedTestResult, s, 'Oops')), +                ('trhee', self.flip_n_switch(1))], +                name='seq')]) +        result_set_error = test.run([make_seqtc([ +                ('one', self.flip_n_switch(0)), +                ('two', lambda s: test.TestResult.make_error(test.UnhandledExceptionTestResult, s, Exception, Exception(), None))], +                name = 'seq')]) +         +         +         +        compound_set = pretty_print_to_string(result_set) +        compound_set_fail = pretty_print_to_string(result_set_fail) +        compound_set_error = pretty_print_to_string(result_set_error) +         +        self.assertEqual(compound_set, textwrap.dedent('''\ +            Passed: 1 +            Errors: 0 +            Failed: 0 +            Skipped: 0 +            ''')) +        self.assertEqual(compound_set_fail, textwrap.dedent('''\ +            Passed: 0 +            Errors: 0 +            Failed: 1 +            Skipped: 0 +            ============================================================ +            fail: seq +            ------------------------------------------------------------ +            pass: one +            fail: two +            Oops +            ------------------------------------------------------------ +            ''')) +        self.assertEqual(compound_set_error, textwrap.dedent('''\ +            Passed: 0 +            Errors: 1 +            Failed: 0 +            Skipped: 0 +            ============================================================ +            error: seq +            ------------------------------------------------------------ +            pass: one +            error: two +            <class 'Exception'>:  +            ------------------------------------------------------------ +            ''')) +     +    def tearDown(self): +        util.rmtemp() + +if __name__ == '__main__': +    unittest.main() diff --git a/test-chill/unit-tests/test_util.py b/test-chill/unit-tests/test_util.py new file mode 100644 index 0000000..fbb0c79 --- /dev/null +++ b/test-chill/unit-tests/test_util.py @@ -0,0 +1,107 @@ +import os +import subprocess +import tempfile +import unittest + +import testchill.util as util + +### Most of these are sanity checks. ### + +class TestUtil(unittest.TestCase): +    def setUp(self): +        self.tempfiles = [] +     +    def maketempfiles(self, n=1): +        files = tuple([tempfile.mkstemp(text=True) for i in range(n)]) +        self.tempfiles += list(map(lambda f: f[1], files)) +        return files +         +    def test_shell(self): +        sbla = subprocess.check_output(['ls', '-la', 'test-cases/chill']) +         +        if util.python_version_major == 3: +            sbla = sbla.decode() +         +        shla = util.shell('ls', ['-la', 'test-cases/chill']) +        self.assertEqual(sbla, shla) +     +    def test_shell_env(self): +        env = {'STRING_VAR':'string','NUMBER_VAR':3,'DEFINED_VAR':1} +         +        self.assertEqual(util.shell('echo', ['$STRING_VAR'], env=env), env['STRING_VAR'] + '\n') +        self.assertEqual(util.shell('echo', ['$NUMBER_VAR'], env=env), str(env['NUMBER_VAR']) + '\n') +        self.assertEqual(util.shell('echo', ['$DEFINED_VAR'], env=env), str(env['DEFINED_VAR']) + '\n') +     +    def test_shell_tofile(self): +        tfile = self.maketempfiles(1) +        fname = tfile[0][1] +         +        with open(fname, 'w') as f: +            util.shell('ls', ['-la', 'test-cases/chill'], stdout=f) +        with open(fname, 'r') as f: +            self.assertEqual(util.shell('ls', ['-la', 'test-cases/chill']), f.read()) +     +    def test_copy(self): +        class C(object): +            pass +        c = C() +        c.x = 'x' +        a = util.copy(c) +        b = util.copy(c) +        a.x = 'y' +        self.assertEqual(c.x,'x') +        self.assertEqual(b.x,'x') +        self.assertEqual(a.x,'y') +     +    def test_callonce(self): +        def foo(): +            return 3 +        foo_once = util.callonce(foo) +        self.assertEqual(foo_once(), 3) +        self.assertRaises(Exception, foo_once) +     +    def test_isdiff(self): +        testdata = [ +                (('aaa','aaa'),(False,'  aaa')), +                (('aab','aaa'),(True, '- aab\n+ aaa')), +                (('a\nb','a\nb\nc'),(True, '  a\n  b\n+ c')), +                (('a\na\nc','a\nb\nc'),(True, '  a\n- a\n+ b\n  c')) +            ] +        for args, expected in testdata: +            isdiff_exp, diff_exp = expected +            isdiff_val, diff_val = util.isdiff(*args) +            self.assertEqual(isdiff_val, isdiff_exp) +            self.assertEqual(diff_val, diff_exp) +     +    def test_filterext(self): +        testdata = [ +                ((['.c','.py'],['a.c','b.txt','c.py']),['a.c','c.py']) +            ] +        for args, expected in testdata: +            self.assertEqual(list(util.filterext(*args)), expected) +     +    #TODO: +    #def test_extract_tag(self): +    #    testdata = [ +    #            (('a', 'abc<a>def</a>ghi<b>jkl</b>mno<c>pqr</c>stu<b>zwx</b>yz'), ['def']), +    #            (('b', 'abc<a>def</a>ghi<b>jkl</b>mno<c>pqr</c>stu<b>zwx</b>yz'), ['jkl','zwx']), +    #            (('c', 'abc<a>def</a>ghi<b>jkl</b>mno<c>pqr</c>stu<b>zwx</b>yz'), ['pqr']), +    #            (('d', 'abc<a>def</a>ghi<b>jkl</b>mno<c>pqr</c>stu<b>zwx</b>yz'), []), +    #        ] +    #    for args, expected in testdata: +    #        self.assertEqual(list(util.extract_tag(*args)), expected) +     +    def test_textstream(self): +        testdata = [ +                (('asdf',),'asdf') +            ] +        for args, expected in testdata: +            stream = util.textstream(*args) +            self.assertTrue(hasattr(stream,'read')) +            self.assertEqual(stream.read(), expected) +     +    def tearDown(self): +        for f in self.tempfiles: +            os.remove(f) +     + | 
