diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 91ef26d2..5ea5226e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -233,10 +233,28 @@ jobs: fi # run specialized role based tests make test-authorization ARGS="--grip_config_file_path test/badger-auth.yml" - - - + pygripTest: + needs: build + name: PyGrip UnitTest + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v2 + - name: Python Dependencies for Conformance + run: pip install requests numpy PyYAML + - name: install gripql + run: | + cd gripql/python + python setup.py install --user + - name: install pygrip + run: | + python setup.py install --user + - name: unit tests + run: | + cd test + python -m unittest discover -s ./pygrip_test + #gridsTest: # needs: build # name: GRIDs Conformance diff --git a/gripql/python/gripql/__init__.py b/gripql/python/gripql/__init__.py index 8cc78e54..bbacd739 100644 --- a/gripql/python/gripql/__init__.py +++ b/gripql/python/gripql/__init__.py @@ -36,4 +36,4 @@ count ] -__version__ = "0.7.1" +__version__ = "0.8.0" diff --git a/gripql/python/gripql/graph.py b/gripql/python/gripql/graph.py index 2b64d02b..ccfd20ca 100644 --- a/gripql/python/gripql/graph.py +++ b/gripql/python/gripql/graph.py @@ -179,6 +179,12 @@ def query(self): """ return Query(self.base_url, self.graph, self.user, self.password, self.token, self.credential_file) + def V(self, *args): + """ + Create a vertex query handle. + """ + return Query(self.base_url, self.graph, self.user, self.password, self.token, self.credential_file).V(*args) + def resume(self, job_id): """ Create a query handle. diff --git a/gripql/python/gripql/query.py b/gripql/python/gripql/query.py index b9e8f1bc..728658d8 100644 --- a/gripql/python/gripql/query.py +++ b/gripql/python/gripql/query.py @@ -36,16 +36,12 @@ def _wrap_dict_value(value): return _wrap_value(value, dict) -class Query(BaseConnection): - def __init__(self, url, graph, user=None, password=None, token=None, credential_file=None, resume=None): - super(Query, self).__init__(url, user, password, token, credential_file) - self.url = self.base_url + "/v1/graph/" + graph + "/query" - self.graph = graph +class QueryBuilder: + def __init__(self): self.query = [] - self.resume = resume def __append(self, part): - q = self.__class__(self.base_url, self.graph, self.user, self.password, self.token, self.credential_file, self.resume) + q = self._builder() q.query = self.query[:] q.query.append(part) return q @@ -343,6 +339,20 @@ def to_dict(self): """ return {"query": self.query} + + +class Query(BaseConnection, QueryBuilder): + def __init__(self, url, graph, user=None, password=None, token=None, credential_file=None, resume=None): + super(Query, self).__init__(url, user, password, token, credential_file) + super(QueryBuilder, self).__init__() + self.url = self.base_url + "/v1/graph/" + graph + "/query" + self.graph = graph + self.query = [] + self.resume = resume + + def _builder(self): + return self.__class__(self.base_url, self.graph, self.user, self.password, self.token, self.credential_file, self.resume) + def __iter__(self): return self.__stream() diff --git a/kvi/leveldb/memdb.go b/kvi/leveldb/memdb.go new file mode 100644 index 00000000..66e8c275 --- /dev/null +++ b/kvi/leveldb/memdb.go @@ -0,0 +1,168 @@ +package leveldb + +import ( + "bytes" + "fmt" + + "github.com/bmeg/grip/kvi" + "github.com/bmeg/grip/log" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/memdb" +) + +var mem_loaded = kvi.AddKVDriver("memdb", NewMemKVInterface) + +type LevelMemKV struct { + db *memdb.DB +} + +// NewKVInterface creates new LevelDB backed KVInterface at `path` +func NewMemKVInterface(path string, opts kvi.Options) (kvi.KVInterface, error) { + log.Info("Starting In-Memory LevelDB") + db := memdb.New(comparer.DefaultComparer, 1000) + return &LevelMemKV{db: db}, nil +} + +// BulkWrite implements kvi.KVInterface. +func (l *LevelMemKV) BulkWrite(u func(bl kvi.KVBulkWrite) error) error { + ktx := &memIterator{l.db, nil, true, nil, nil} + return u(ktx) +} + +// Close implements kvi.KVInterface. +func (l *LevelMemKV) Close() error { + return nil +} + +// Delete implements kvi.KVInterface. +func (l *LevelMemKV) Delete(key []byte) error { + return l.db.Delete(key) +} + +// DeletePrefix implements kvi.KVInterface. +func (l *LevelMemKV) DeletePrefix(prefix []byte) error { + deleteBlockSize := 10000 + for found := true; found; { + found = false + wb := make([][]byte, 0, deleteBlockSize) + it := l.db.NewIterator(nil) + for it.Seek(prefix); it.Valid() && bytes.HasPrefix(it.Key(), prefix) && len(wb) < deleteBlockSize-1; it.Next() { + wb = append(wb, copyBytes(it.Key())) + } + it.Release() + for _, i := range wb { + l.db.Delete(i) + found = true + } + } + return nil + +} + +// Get implements kvi.KVInterface. +func (l *LevelMemKV) Get(key []byte) ([]byte, error) { + return l.db.Get(key) +} + +// HasKey implements kvi.KVInterface. +func (l *LevelMemKV) HasKey(key []byte) bool { + _, err := l.db.Get(key) + return err == nil +} + +// Set implements kvi.KVInterface. +func (l *LevelMemKV) Set(key []byte, value []byte) error { + return l.db.Put(key, value) +} + +// Update implements kvi.KVInterface. +func (l *LevelMemKV) Update(func(tx kvi.KVTransaction) error) error { + panic("unimplemented") +} + +// View implements kvi.KVInterface. +func (l *LevelMemKV) View(u func(it kvi.KVIterator) error) error { + it := l.db.NewIterator(nil) + defer it.Release() + lit := memIterator{l.db, it, true, nil, nil} + return u(&lit) +} + +type memIterator struct { + db *memdb.DB + it iterator.Iterator + forward bool + key []byte + value []byte +} + +// Get retrieves the value of key `id` +func (lit *memIterator) Get(id []byte) ([]byte, error) { + return lit.db.Get(id) +} + +func (lit *memIterator) Set(key, val []byte) error { + return lit.db.Put(key, val) +} + +// Key returns the key the iterator is currently pointed at +func (lit *memIterator) Key() []byte { + return lit.key +} + +// Value returns the valud of the iterator is currently pointed at +func (lit *memIterator) Value() ([]byte, error) { + return lit.value, nil +} + +// Next move the iterator to the next key +func (lit *memIterator) Next() error { + var more bool + if lit.forward { + more = lit.it.Next() + } else { + more = lit.it.Prev() + } + if !more { + lit.key = nil + lit.value = nil + return fmt.Errorf("Invalid") + } + lit.key = copyBytes(lit.it.Key()) + lit.value = copyBytes(lit.it.Value()) + return nil +} + +func (lit *memIterator) Seek(id []byte) error { + lit.forward = true + if lit.it.Seek(id) { + lit.key = copyBytes(lit.it.Key()) + lit.value = copyBytes(lit.it.Value()) + return nil + } + return fmt.Errorf("Invalid") +} + +func (lit *memIterator) SeekReverse(id []byte) error { + lit.forward = false + if lit.it.Seek(id) { + //Level iterator will land on the first value above the request + //if we're there, move once to get below start request + if bytes.Compare(id, lit.it.Key()) < 0 { + lit.it.Prev() + } + lit.key = copyBytes(lit.it.Key()) + lit.value = copyBytes(lit.it.Value()) + return nil + } + return fmt.Errorf("Invalid") +} + +// Valid returns true if iterator is still in valid location +func (lit *memIterator) Valid() bool { + if lit.key == nil || lit.value == nil { + return false + } + return true +} diff --git a/pygrip/Makefile b/pygrip/Makefile new file mode 100644 index 00000000..e3d2cad1 --- /dev/null +++ b/pygrip/Makefile @@ -0,0 +1,4 @@ + + +pygrip.so: wrapper.go + go build -o pygrip.so -buildmode=c-shared wrapper.go diff --git a/pygrip/__init__.py b/pygrip/__init__.py new file mode 100644 index 00000000..33964bf1 --- /dev/null +++ b/pygrip/__init__.py @@ -0,0 +1,74 @@ + + +from __future__ import print_function +from ctypes import * +from ctypes.util import find_library +import os, inspect, sysconfig +import random, string +import json +from gripql.query import QueryBuilder + +cwd = os.getcwd() +currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) +#print("frame: %s" % (inspect.getfile(inspect.currentframe()))) +#print("cd to %s" % (currentdir)) +os.chdir(currentdir) +_lib = cdll.LoadLibrary("./_pygrip" + sysconfig.get_config_vars()["EXT_SUFFIX"]) +os.chdir(cwd) + +_lib.ReaderNext.restype = c_char_p + +class GoString(Structure): + _fields_ = [("p", c_char_p), ("n", c_longlong)] + +def NewMemServer(): + return GraphDBWrapper( _lib.NewMemServer() ) + +def getGoString(s): + return GoString(bytes(s, encoding="raw_unicode_escape"), len(s)) + +def id_generator(size=6, chars=string.ascii_uppercase + string.digits): + return ''.join(random.choice(chars) for _ in range(size)) + +class QueryWrapper(QueryBuilder): + def __init__(self, wrapper): + super(QueryBuilder, self).__init__() + self.query = [] + self.wrapper = wrapper + + def __iter__(self): + jquery = json.dumps({ "graph" : "default", "query" : self.query }) + reader = _lib.Query( self.wrapper._handle, getGoString(jquery) ) + while not _lib.ReaderDone(reader): + j = _lib.ReaderNext(reader) + yield json.loads(j) + + def _builder(self): + return QueryWrapper(self.wrapper) + +class GraphDBWrapper: + def __init__(self, handle) -> None: + self._handle = handle + + def addVertex(self, gid, label, data={}): + """ + Add vertex to a graph. + """ + _lib.AddVertex(self._handle, getGoString(gid), getGoString(label), + getGoString(json.dumps(data))) + + def addEdge(self, src, dst, label, data={}, gid=None): + """ + Add edge to a graph. + """ + if gid is None: + gid = id_generator(10) + + _lib.AddEdge(self._handle, getGoString(gid), + getGoString(src), getGoString(dst), getGoString(label), + getGoString(json.dumps(data))) + + + + def V(self, *ids): + return QueryWrapper(self).V(*ids) \ No newline at end of file diff --git a/pygrip/pygrip.h b/pygrip/pygrip.h new file mode 100644 index 00000000..db6abcf1 --- /dev/null +++ b/pygrip/pygrip.h @@ -0,0 +1,86 @@ +/* Code generated by cmd/cgo; DO NOT EDIT. */ + +/* package command-line-arguments */ + + +#line 1 "cgo-builtin-export-prolog" + +#include + +#ifndef GO_CGO_EXPORT_PROLOGUE_H +#define GO_CGO_EXPORT_PROLOGUE_H + +#ifndef GO_CGO_GOSTRING_TYPEDEF +typedef struct { const char *p; ptrdiff_t n; } _GoString_; +#endif + +#endif + +/* Start of preamble from import "C" comments. */ + + + + +/* End of preamble from import "C" comments. */ + + +/* Start of boilerplate cgo prologue. */ +#line 1 "cgo-gcc-export-header-prolog" + +#ifndef GO_CGO_PROLOGUE_H +#define GO_CGO_PROLOGUE_H + +typedef signed char GoInt8; +typedef unsigned char GoUint8; +typedef short GoInt16; +typedef unsigned short GoUint16; +typedef int GoInt32; +typedef unsigned int GoUint32; +typedef long long GoInt64; +typedef unsigned long long GoUint64; +typedef GoInt64 GoInt; +typedef GoUint64 GoUint; +typedef size_t GoUintptr; +typedef float GoFloat32; +typedef double GoFloat64; +#ifdef _MSC_VER +#include +typedef _Fcomplex GoComplex64; +typedef _Dcomplex GoComplex128; +#else +typedef float _Complex GoComplex64; +typedef double _Complex GoComplex128; +#endif + +/* + static assertion to make sure the file is being used on architecture + at least with matching size of GoInt. +*/ +typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1]; + +#ifndef GO_CGO_GOSTRING_TYPEDEF +typedef _GoString_ GoString; +#endif +typedef void *GoMap; +typedef void *GoChan; +typedef struct { void *t; void *v; } GoInterface; +typedef struct { void *data; GoInt len; GoInt cap; } GoSlice; + +#endif + +/* End of boilerplate cgo prologue. */ + +#ifdef __cplusplus +extern "C" { +#endif + +extern GoUintptr NewMemServer(); +extern void AddVertex(GoUintptr graph, GoString gid, GoString label, GoString jdata); +extern void AddEdge(GoUintptr graph, GoString gid, GoString src, GoString dst, GoString label, GoString jdata); +extern GoUintptr Query(GoUintptr graph, GoString jquery); +extern GoUint8 ReaderDone(GoUintptr reader); +extern char* ReaderNext(GoUintptr reader); + +#ifdef __cplusplus +} +#endif diff --git a/pygrip/wrapper.go b/pygrip/wrapper.go new file mode 100644 index 00000000..0657f2c8 --- /dev/null +++ b/pygrip/wrapper.go @@ -0,0 +1,162 @@ +package main + +/* +#include // for uintptr_t +*/ + +import "C" + +import ( + "context" + "encoding/json" + + "runtime/cgo" + + "github.com/bmeg/grip/engine" + "github.com/bmeg/grip/engine/core" + "github.com/bmeg/grip/engine/pipeline" + "github.com/bmeg/grip/gdbi" + "github.com/bmeg/grip/gripql" + "github.com/bmeg/grip/kvgraph" + "github.com/bmeg/grip/kvi" + "github.com/bmeg/grip/kvi/leveldb" + "github.com/bmeg/grip/log" + "google.golang.org/protobuf/encoding/protojson" +) + +var graphDB gdbi.GraphDB + +type GraphHandle uintptr +type QueryReaderHandle uintptr + +type Reader interface { + Done() bool + Next() string +} + +//export NewMemServer +func NewMemServer() GraphHandle { + db, _ := leveldb.NewMemKVInterface("", kvi.Options{}) + graphDB = kvgraph.NewKVGraph(db) + err := graphDB.AddGraph("default") + if err != nil { + log.Errorf("Graph init error: %s\n", err) + } + g, err := graphDB.Graph("default") + if err != nil { + log.Errorf("Graph init error: %s\n", err) + } + return GraphHandle(cgo.NewHandle(g)) +} + +func CloseServer(graph GraphHandle) { + cgo.Handle(graph).Delete() +} + +//export AddVertex +func AddVertex(graph GraphHandle, gid, label, jdata string) { + data := map[string]any{} + err := json.Unmarshal([]byte(jdata), &data) + if err != nil { + log.Errorf("Data error: %s : %s\n", err, jdata) + } + + g := cgo.Handle(graph).Value().(gdbi.GraphInterface) + + g.AddVertex([]*gdbi.Vertex{ + {ID: gid, Label: label, Data: data}, + }) +} + +//export AddEdge +func AddEdge(graph GraphHandle, gid, src, dst, label, jdata string) { + data := map[string]any{} + err := json.Unmarshal([]byte(jdata), &data) + if err != nil { + log.Errorf("Data error: %s : %s\n", err, jdata) + } + + g := cgo.Handle(graph).Value().(gdbi.GraphInterface) + + g.AddEdge([]*gdbi.Edge{ + {ID: gid, To: dst, From: src, Label: label, Data: data}, + }) +} + +type QueryReader struct { + pipe gdbi.Pipeline + results chan *gripql.QueryResult + current *gripql.QueryResult +} + +//export Query +func Query(graph GraphHandle, jquery string) QueryReaderHandle { + query := gripql.GraphQuery{} + err := protojson.Unmarshal([]byte(jquery), &query) + if err != nil { + log.Errorf("Query error: %s : %s\n", err) + } + + g := cgo.Handle(graph).Value().(gdbi.GraphInterface) + compiler := core.NewCompiler(g) + pipe, err := compiler.Compile(query.Query, nil) + if err != nil { + log.Errorf("Compile error: %s : %s\n", err) + } + + ctx := context.Background() + + bufsize := 5000 + resch := make(chan *gripql.QueryResult, bufsize) + go func() { + defer close(resch) + graph := pipe.Graph() + dataType := pipe.DataType() + markTypes := pipe.MarkTypes() + man := engine.NewManager("./") //TODO: in memory option + rPipe := pipeline.Start(ctx, pipe, man, bufsize, nil, nil) + for t := range rPipe.Outputs { + if !t.IsSignal() { + resch <- pipeline.Convert(graph, dataType, markTypes, t) + } + } + man.Cleanup() + }() + var o = &QueryReader{ + pipe: pipe, + results: resch, + current: nil, + } + return QueryReaderHandle(cgo.NewHandle(o)) +} + +//export ReaderDone +func ReaderDone(reader QueryReaderHandle) bool { + r := cgo.Handle(reader).Value().(*QueryReader) + return r.Done() +} + +//export ReaderNext +func ReaderNext(reader QueryReaderHandle) *C.char { + r := cgo.Handle(reader).Value().(*QueryReader) + o := r.Next() + return C.CString(o) +} + +func (r *QueryReader) Next() string { + out, _ := protojson.Marshal(r.current) + return string(out) +} + +func (r *QueryReader) Done() bool { + select { + case i, ok := <-r.results: + if ok { + r.current = i + return false + } + return true + } +} + +func main() {} diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 00000000..fdfcb650 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +pythonpath = . gripql/python grip diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..4dba5c58 --- /dev/null +++ b/setup.py @@ -0,0 +1,33 @@ +"""Setup for checksig package""" +import sys +from distutils.errors import CompileError +from subprocess import call + +from setuptools import Extension, setup, find_packages +from setuptools.command.build_ext import build_ext + + +class build_go_ext(build_ext): + """Custom command to build extension from Go source files""" + def build_extension(self, ext): + ext_path = self.get_ext_fullpath(ext.name) + cmd = ['go', 'build', '-buildmode=c-shared', '-o', ext_path] + cmd += ext.sources + out = call(cmd) + if out != 0: + raise CompileError('Go build failed') + +setup( + name='pygrip', + version='0.8.0', + packages=find_packages(include=['pygrip']), + #py_modules=['pygrip'], + ext_modules=[ + Extension('pygrip/_pygrip', ['./pygrip/wrapper.go']) + ], + cmdclass={'build_ext': build_go_ext}, + install_requires=[ + "gripql>=0.8.0" + ], + zip_safe=False, +) \ No newline at end of file diff --git a/test/__init__.py b/test/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/test/pygrip_test/__init__.py b/test/pygrip_test/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/test/pygrip_test/fhir/README.md b/test/pygrip_test/fhir/README.md new file mode 100644 index 00000000..c4113497 --- /dev/null +++ b/test/pygrip_test/fhir/README.md @@ -0,0 +1,5 @@ +This test has a dependency +```commandline +pip install jsonpath-ng + +``` \ No newline at end of file diff --git a/test/pygrip_test/fhir/__init__.py b/test/pygrip_test/fhir/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/DocumentReference.ndjson b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/DocumentReference.ndjson new file mode 100644 index 00000000..8da14c2b --- /dev/null +++ b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/DocumentReference.ndjson @@ -0,0 +1 @@ +{"resourceType":"DocumentReference","id":"9ae7e542-767f-4b03-a854-7ceed17152cb","identifier":[{"use":"official","system":"https://my_demo.org/labA","value":"9ae7e542-767f-4b03-a854-7ceed17152cb"}],"status":"current","docStatus":"final","subject":{"reference":"Specimen/60c67a06-ea2d-4d24-9249-418dc77a16a9"},"date":"2024-08-21T10:53:00+00:00","content":[{"attachment":{"extension":[{"url":"http://aced-idp.org/fhir/StructureDefinition/md5","valueString":"227f0a5379362d42eaa1814cfc0101b8"},{"url":"http://aced-idp.org/fhir/StructureDefinition/source_path","valueUrl":"file:///home/LabA/specimen_1234_labA.fq.gz"}],"contentType":"text/fastq","url":"file:///home/LabA/specimen_1234_labA.fq.gz","size":5595609484,"title":"specimen_1234_labA.fq.gz","creation":"2024-08-21T10:53:00+00:00"}}]} \ No newline at end of file diff --git a/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Observation.ndjson b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Observation.ndjson new file mode 100644 index 00000000..774b7051 --- /dev/null +++ b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Observation.ndjson @@ -0,0 +1,3 @@ +{"resourceType":"Observation","id":"cec32723-9ede-5f24-ba63-63cb8c6a02cf","identifier":[{"use":"official","system":"https://my_demo.org/labA","value":"patientX_1234-9ae7e542-767f-4b03-a854-7ceed17152cb-sequencer"}], "status":"final","category":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/observation-category","code":"laboratory","display":"Laboratory"}]}],"code":{"coding":[{"system":"https://my_demo.org/labA","code":"Gen3 Sequencing Metadata","display":"Gen3 Sequencing Metadata"}]},"subject":{"reference":"Patient/bc4e1aa6-cb52-40e9-8f20-594d9c84f920"},"focus":[{"reference":"DocumentReference/9ae7e542-767f-4b03-a854-7ceed17152cb"}],"specimen":{"reference":"Specimen/60c67a06-ea2d-4d24-9249-418dc77a16a9"},"component":[{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"sequencer","display":"sequencer"}],"text":"sequencer"},"valueString":"Illumina Seq 1000"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"index","display":"index"}],"text":"index"},"valueString":"100bp Single index"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"type","display":"type"}],"text":"type"},"valueString":"Exome"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"project_id","display":"project_id"}],"text":"project_id"},"valueString":"labA_projectXYZ"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"read_length","display":"read_length"}],"text":"read_length"},"valueString":"100"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"instrument_run_id","display":"instrument_run_id"}],"text":"instrument_run_id"},"valueString":"234_ABC_1_8899"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"capture_bait_set","display":"capture_bait_set"}],"text":"capture_bait_set"},"valueString":"Human Exom 2X"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"end_type","display":"end_type"}],"text":"end_type"},"valueString":"Paired-End"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"capture","display":"capture"}],"text":"capture"},"valueString":"emitter XT"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"sequencing_site","display":"sequencing_site"}],"text":"sequencing_site"},"valueString":"AdvancedGeneExom"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"construction","display":"construction"}],"text":"construction"},"valueString":"library_construction"}]} +{"resourceType":"Observation","id":"4e3c6b59-b1fd-5c26-a611-da4cde9fd061","identifier":[{"use":"official","system":"https://my_demo.org/labA","value":"patientX_1234-specimen_1234_labA-sample_type"}],"status":"final","category":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/observation-category","code":"laboratory","display":"Laboratory"}],"text":"Laboratory"}],"code":{"coding":[{"system":"https://my_demo.org/labA","code":"labA specimen metadata","display":"labA specimen metadata"}],"text":"sample type abc"},"subject":{"reference":"Patient/bc4e1aa6-cb52-40e9-8f20-594d9c84f920"},"focus":[{"reference":"Specimen/60c67a06-ea2d-4d24-9249-418dc77a16a9"}],"component":[{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"sample_type","display":"sample_type"}],"text":"sample_type"},"valueString":"Primary Solid Tumor"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"library_id","display":"library_id"}],"text":"library_id"},"valueString":"12345"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"tissue_type","display":"tissue_type"}],"text":"tissue_type"},"valueString":"Tumor"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"treatments","display":"treatments"}],"text":"treatments"},"valueString":"Trastuzumab"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"allocated_for_site","display":"allocated_for_site"}],"text":"allocated_for_site"},"valueString":"TEST Clinical Research"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"pathology_data","display":"pathology_data"}],"text":"pathology_data"}},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"clinical_event","display":"clinical_event"}],"text":"clinical_event"}},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"indexed_collection_date","display":"indexed_collection_date"}],"text":"indexed_collection_date"},"valueInteger":365},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"biopsy_specimens_bems_id","display":"biopsy_specimens_bems_id"}],"text":"biopsy_specimens"},"valueString":"specimenA, specimenB, specimenC"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"biopsy_procedure_type","display":"biopsy_procedure_type"}],"text":"biopsy_procedure_type"},"valueString":"Biopsy - Core"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"biopsy_anatomical_location","display":"biopsy_anatomical_location"}],"text":"biopsy_anatomical_location"},"valueString":"top axillary lymph node"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"percent_tumor","display":"percent_tumor"}],"text":"percent_tumor"},"valueString":"30"}]} +{"resourceType":"Observation","id":"21f3411d-89a4-4bcc-9ce7-b76edb1c745f","identifier":[{"use":"official","system":"https://my_demo.org/labA","value":"patientX_1234-9ae7e542-767f-4b03-a854-7ceed17152cb-Gene"}], "status":"final","category":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/observation-category","code":"laboratory","display":"Laboratory"}]}],"code":{"coding":[{"system":"https://loinc.org","code":"81247-9","display":"Genomic structural variant copy number"}]},"subject":{"reference":"Patient/bc4e1aa6-cb52-40e9-8f20-594d9c84f920"},"focus":[{"reference":"DocumentReference/9ae7e542-767f-4b03-a854-7ceed17152cb"}],"specimen":{"reference":"Specimen/60c67a06-ea2d-4d24-9249-418dc77a16a9"},"component":[{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"Gene","display":"Gene"}],"text":"Gene"},"valueString":"TP53"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"Chromosome","display":"Chromosome"}],"text":"Chromosome"},"valueString":"chr17"},{"code":{"coding":[{"system":"https://my_demo.org/labA","code":"result","display":"result"}],"text":"result"},"valueString":"gain of function (GOF)"}]} \ No newline at end of file diff --git a/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Organization.ndjson b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Organization.ndjson new file mode 100644 index 00000000..967445ae --- /dev/null +++ b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Organization.ndjson @@ -0,0 +1 @@ +{"resourceType":"Organization","id":"89c8dc4c-2d9c-48c7-8862-241a49a78f14","identifier":[{"use":"official","system":"https://my_demo.org/labA","value":"LabA_ORGANIZATION"}],"type":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/organization-type","code":"prov","display":"Healthcare Provider"}],"text":"An organization that provides healthcare services."},{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/organization-type","code":"edu","display":"Educational Institute"}],"text":"An educational institution that provides education or research facilities."}]} \ No newline at end of file diff --git a/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Patient.ndjson b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Patient.ndjson new file mode 100644 index 00000000..107bf78e --- /dev/null +++ b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Patient.ndjson @@ -0,0 +1 @@ +{"resourceType":"Patient","id":"bc4e1aa6-cb52-40e9-8f20-594d9c84f920","identifier":[{"use":"official","system":"https://my_demo.org/labA","value":"patientX_1234"}],"active":true} \ No newline at end of file diff --git a/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/ResearchStudy.ndjson b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/ResearchStudy.ndjson new file mode 100644 index 00000000..74cc4002 --- /dev/null +++ b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/ResearchStudy.ndjson @@ -0,0 +1 @@ +{"resourceType":"ResearchStudy","id":"7dacd4d0-3c8e-470b-bf61-103891627d45","identifier":[{"use":"official","system":"https://my_demo.org/labA","value":"labA"}],"name":"LabA","status":"active","description":"LabA Clinical Trial Study: FHIR Schema Chorot Integration"} \ No newline at end of file diff --git a/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/ResearchSubject.ndjson b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/ResearchSubject.ndjson new file mode 100644 index 00000000..6aee6d08 --- /dev/null +++ b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/ResearchSubject.ndjson @@ -0,0 +1 @@ +{"resourceType":"ResearchSubject","id":"2fc448d6-a23b-4b94-974b-c66110164851","identifier":[{"use":"official","system":"https://my_demo.org/labA","value":"subjectX_1234"}],"status":"active","study":{"reference":"ResearchStudy/7dacd4d0-3c8e-470b-bf61-103891627d45"},"subject":{"reference":"Patient/bc4e1aa6-cb52-40e9-8f20-594d9c84f920"}} \ No newline at end of file diff --git a/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Specimen.ndjson b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Specimen.ndjson new file mode 100644 index 00000000..b79c72cb --- /dev/null +++ b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/META/Specimen.ndjson @@ -0,0 +1 @@ +{"resourceType":"Specimen","id":"60c67a06-ea2d-4d24-9249-418dc77a16a9","identifier":[{"use":"official","system":"https://my_demo.org/labA","value":"specimen_1234_labA"}],"subject":{"reference":"Patient/bc4e1aa6-cb52-40e9-8f20-594d9c84f920"},"collection":{"collector":{"reference":"Organization/89c8dc4c-2d9c-48c7-8862-241a49a78f14"},"bodySite":{"concept":{"coding":[{"system":"http://snomed.info/sct","code":"76752008","display":"Breast"}],"text":"Breast"}}},"processing":[{"method":{"coding":[{"system":"http://snomed.info/sct","code":"117032008","display":"Spun specimen (procedure)"},{"system":"https://my_demo.org/labA","code":"Double-Spun","display":"Double-Spun"}],"text":"Spun specimen (procedure)"}}]} \ No newline at end of file diff --git a/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/README.md b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/README.md new file mode 100644 index 00000000..bcad0e36 --- /dev/null +++ b/test/pygrip_test/fhir/fixtures/fhir-compbio-examples/README.md @@ -0,0 +1,11 @@ +##### META folder test-data: + +``` +>>>> resources={'summary': {'DocumentReference': 1, 'Specimen': 1, 'Observation': 3, 'ResearchStudy': 1, 'ResearchSubject': 1, 'Organization': 1, 'Patient': 1}} +``` + +There are three Observations with user-defined metadata component. +1. Focus - reference -> Specimen +2. Focus - reference -> DocumentReference + 1. The first Observation contains metadata on the file's sequencing metadata. + 2. The second Observation includes a simple summary of a CNV analysis result computed from this file. diff --git a/test/pygrip_test/fhir/test_load.py b/test/pygrip_test/fhir/test_load.py new file mode 100644 index 00000000..4b32d0b8 --- /dev/null +++ b/test/pygrip_test/fhir/test_load.py @@ -0,0 +1,271 @@ +import json +import pathlib +import types +from collections import defaultdict + +import pytest + +import pygrip +from jsonpath_ng import jsonpath, parse + +from typing import Generator, Dict, Any + + +def resources() -> Generator[Dict[str, Any], None, None]: + """Read a directory of ndjson files, return dictionary for each line.""" + base = pathlib.Path(__file__).parent.absolute() + fixture_path = pathlib.Path(base / 'fixtures' / 'fhir-compbio-examples' / 'META') + assert fixture_path.exists(), f"Fixture path {fixture_path.absolute()} does not exist." + for file in fixture_path.glob('*.ndjson'): + with open(str(file)) as fp: + for l_ in fp.readlines(): + yield json.loads(l_) + + +@pytest.fixture +def expected_edges() -> list[tuple]: + """Return the expected edges for the resources [(src, dst, label)].""" + return [('21f3411d-89a4-4bcc-9ce7-b76edb1c745f', '60c67a06-ea2d-4d24-9249-418dc77a16a9', 'specimen'), + ('21f3411d-89a4-4bcc-9ce7-b76edb1c745f', '9ae7e542-767f-4b03-a854-7ceed17152cb', 'focus'), + ('21f3411d-89a4-4bcc-9ce7-b76edb1c745f', 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920', 'subject'), + ('2fc448d6-a23b-4b94-974b-c66110164851', '7dacd4d0-3c8e-470b-bf61-103891627d45', 'study'), + ('2fc448d6-a23b-4b94-974b-c66110164851', 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920', 'subject'), + ('4e3c6b59-b1fd-5c26-a611-da4cde9fd061', '60c67a06-ea2d-4d24-9249-418dc77a16a9', 'focus'), + ('4e3c6b59-b1fd-5c26-a611-da4cde9fd061', 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920', 'subject'), + ('60c67a06-ea2d-4d24-9249-418dc77a16a9', '89c8dc4c-2d9c-48c7-8862-241a49a78f14', 'collection_collector'), + ('60c67a06-ea2d-4d24-9249-418dc77a16a9', 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920', 'subject'), + ('9ae7e542-767f-4b03-a854-7ceed17152cb', '60c67a06-ea2d-4d24-9249-418dc77a16a9', 'subject'), + ('cec32723-9ede-5f24-ba63-63cb8c6a02cf', '60c67a06-ea2d-4d24-9249-418dc77a16a9', 'specimen'), + ('cec32723-9ede-5f24-ba63-63cb8c6a02cf', '9ae7e542-767f-4b03-a854-7ceed17152cb', 'focus'), + ('cec32723-9ede-5f24-ba63-63cb8c6a02cf', 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920', 'subject')] + + +@pytest.fixture +def expected_vertices() -> list[tuple]: + """Return the expected vertices [(id, label)] for the resources.""" + return [('21f3411d-89a4-4bcc-9ce7-b76edb1c745f', 'Observation'), + ('2fc448d6-a23b-4b94-974b-c66110164851', 'ResearchSubject'), + ('4e3c6b59-b1fd-5c26-a611-da4cde9fd061', 'Observation'), + ('60c67a06-ea2d-4d24-9249-418dc77a16a9', 'Specimen'), + ('7dacd4d0-3c8e-470b-bf61-103891627d45', 'ResearchStudy'), + ('89c8dc4c-2d9c-48c7-8862-241a49a78f14', 'Organization'), + ('9ae7e542-767f-4b03-a854-7ceed17152cb', 'DocumentReference'), + ('bc4e1aa6-cb52-40e9-8f20-594d9c84f920', 'Patient'), + ('cec32723-9ede-5f24-ba63-63cb8c6a02cf', 'Observation')] + + +@pytest.fixture +def expected_dataframe_associations(): + """Return the expected dataframe associations for the resources. { (resource_type, resource_id): [(association_resource_type, association_resource_id)].""" + return { + ('ResearchSubject', '2fc448d6-a23b-4b94-974b-c66110164851'): [ + ('ResearchStudy', '7dacd4d0-3c8e-470b-bf61-103891627d45'), + ('Patient', 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920'), + ('Specimen', '60c67a06-ea2d-4d24-9249-418dc77a16a9')], + ('Specimen', '60c67a06-ea2d-4d24-9249-418dc77a16a9'): [ + ('ResearchStudy', '7dacd4d0-3c8e-470b-bf61-103891627d45'), + ('ResearchSubject', '2fc448d6-a23b-4b94-974b-c66110164851'), + ('Patient', 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920'), + ('Observation', '4e3c6b59-b1fd-5c26-a611-da4cde9fd061')], + ('ResearchStudy', '7dacd4d0-3c8e-470b-bf61-103891627d45'): [ + ('ResearchSubject', '2fc448d6-a23b-4b94-974b-c66110164851')], + ('Organization', '89c8dc4c-2d9c-48c7-8862-241a49a78f14'): [ + ('ResearchStudy', '7dacd4d0-3c8e-470b-bf61-103891627d45'), + ('ResearchSubject', '2fc448d6-a23b-4b94-974b-c66110164851'), + ('Patient', 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920'), + ('Specimen', '60c67a06-ea2d-4d24-9249-418dc77a16a9'), + ('DocumentReference', '9ae7e542-767f-4b03-a854-7ceed17152cb')], + ('DocumentReference', '9ae7e542-767f-4b03-a854-7ceed17152cb'): [ + ('ResearchStudy', '7dacd4d0-3c8e-470b-bf61-103891627d45'), + ('ResearchSubject', '2fc448d6-a23b-4b94-974b-c66110164851'), + ('Patient', 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920'), + ('Specimen', '60c67a06-ea2d-4d24-9249-418dc77a16a9'), + ('Observation', '21f3411d-89a4-4bcc-9ce7-b76edb1c745f'), + ('Observation', 'cec32723-9ede-5f24-ba63-63cb8c6a02cf')], + ('Patient', 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920'): [ + ('ResearchStudy', '7dacd4d0-3c8e-470b-bf61-103891627d45'), + ('ResearchSubject', '2fc448d6-a23b-4b94-974b-c66110164851'), + ('Specimen', '60c67a06-ea2d-4d24-9249-418dc77a16a9'), + ('Observation', '21f3411d-89a4-4bcc-9ce7-b76edb1c745f'), + ('Observation', '4e3c6b59-b1fd-5c26-a611-da4cde9fd061'), + ('Observation', 'cec32723-9ede-5f24-ba63-63cb8c6a02cf')] + } + + +def match_label(self, vertex_gid, label, seen_already=None) -> dict: + """Recursively find the first vertex of a given label, starting traversals from vertex_gid.""" + + # check params + assert vertex_gid is not None, "Expected vertex_gid to be not None." + assert label is not None, "Expected label to be not None." + # mutable default arguments are evil + # See https://florimond.dev/en/posts/2018/08/python-mutable-defaults-are-the-source-of-all-evil + if seen_already is None: + seen_already = [] + + # get all edges for vertex + q = self.V(vertex_gid).both() + + # get all vertices for edges + # TODO - consider if this should be a vertices_of_label() -> generator[dict] instead + for _ in q: + if _['vertex']['label'] == label: + return _ + else: + if _['vertex']['gid'] in seen_already: + continue + seen_already.append(_['vertex']['gid']) + return self.match_label(_['vertex']['gid'], label, seen_already=seen_already) + + +def dataframe_associations(self, vertex_gid, vertex_label, labels=('ResearchStudy', 'ResearchSubject', 'Patient', 'Specimen', 'DocumentReference', 'Observation')) -> list[dict]: + """Return all objects associated with vertex_gid.""" + associations = [] + for label in labels: + if label == 'Observation': + continue + if vertex_label == label: + continue + _ = self.match_label(vertex_gid, label) + if _ is not None: + associations.append(_['vertex']['data']) + if 'Observation' in labels: + q = self.V(vertex_gid).in_(["focus", "subject"]).hasLabel("Observation") + for _ in q: + associations.append(_['vertex']['data']) + return associations + + +@pytest.fixture +def graph() -> pygrip.GraphDBWrapper: + """Load the resources into the graph. Note: this does _not_ consider iceberg schema.""" + # TODO - add parameter or test environment variable to switch between in-memory and remote graph + graph = pygrip.NewMemServer() + # use jsonpath to find all references with a resource + jsonpath_expr = parse('*..reference') + for _ in resources(): + graph.addVertex(_['id'], _['resourceType'], _) + for match in jsonpath_expr.find(_): + # value will be something like "Specimen/60c67a06-ea2d-4d24-9249-418dc77a16a9" + # full_path will be something like "specimen.reference" or "focus.[0].reference" + type_, dst_id = match.value.split('/') + # determine label from full path + path_parts = str(match.full_path).split('.') + # strip out array indices and reference + path_parts = [part for part in path_parts if '[' not in part and part != 'reference'] + # make it a label + label = '_'.join(path_parts) + graph.addEdge(_['id'], dst_id, label) + + # monkey patch the graph object with our methods + # TODO - consider a more formal subclass of pygrip.GraphDBWrapper + graph.match_label = types.MethodType(match_label, graph) + graph.dataframe_associations = types.MethodType(dataframe_associations, graph) + + yield graph + + +def test_graph_vertices(graph, expected_vertices): + """Test the graph vertices.""" + + actual_vertices = [] + for _ in graph.V(): + assert 'vertex' in _, f"Expected 'vertex' in {_}" + vertex = _['vertex'] + assert 'data' in vertex, f"Expected 'data' in {vertex}" + assert 'gid' in vertex, f"Expected 'gid' in {vertex}" + assert 'label' in vertex, f"Expected 'label' in {vertex}" + assert 'data' in vertex, f"Expected 'data' in {vertex}" + resource = _['vertex']['data'] + actual_vertices.append((resource['id'], resource['resourceType'])) + + print(actual_vertices) + assert actual_vertices == expected_vertices, f"Expected {expected_vertices} but got {actual_vertices}." + + +def test_graph_edges(graph, expected_edges): + """Test the graph vertices.""" + + # check edges all edges + actual_edges = [] + for _ in graph.V().outE(): + assert 'edge' in _, f"Expected 'edge' in {_}" + edge = _['edge'] + assert 'gid' in edge, f"Expected 'gid' in {edge}" + assert 'label' in edge, f"Expected 'label' in {edge}" + assert 'from' in edge, f"Expected 'from' in {edge}" + assert 'to' in edge, f"Expected 'to' in {edge}" + assert 'data' in edge, f"Expected 'data' in {edge}" + + actual_edges.append((edge['from'], edge['to'], edge['label'])) + + print(actual_edges) + assert actual_edges == expected_edges, f"Expected {expected_edges} but got {actual_edges}." + + +def test_graph_methods(graph): + """Test the methods we expect in a graph object.""" + assert 'V' in dir(graph), f"Expected 'V' in {type(graph)}" + assert 'match_label' in dir(graph), f"Expected 'match_label' in {type(graph)}" + assert 'dataframe_associations' in dir(graph), f"Expected 'dataframe_associations' in {type(graph)}" + + +def test_traversals(graph): + """Test basic traversals""" + + # specimen -> patient + q = graph.V().hasLabel("Specimen").out("subject") + actual_specimen_patient_count = len(list(q)) + assert actual_specimen_patient_count == 1, f"Expected 1 but got {actual_specimen_patient_count}." + assert list(q)[0]['vertex']['data']['resourceType'] == 'Patient' + + q = graph.V().hasLabel("DocumentReference").outV().hasLabel("Specimen").outV().hasLabel("Patient") + assert len(list(q)) == 1, f"Expected 1 but got {len(list(q))}." + actual_document_reference_patient_count = len(list(q)) + assert actual_document_reference_patient_count == 1, f"Expected 1 but got {actual_document_reference_patient_count}." + assert list(q)[0]['vertex']['data']['resourceType'] == 'Patient' + + # follow edges by edge label + q = graph.V().hasLabel("DocumentReference").out("subject") + assert len(list(q)) == 1, f"Expected 1 but got {len(list(q))}." + for subject in q: + subject = subject['vertex']['data'] + assert subject['resourceType'] == 'Specimen', f"Expected Specimen but got {subject['resourceType']}." + + # follow all out all edges recursively to a vertex of type X + + q = graph.V().hasLabel("DocumentReference") + assert len(list(q)) == 1, f"Expected 1 but got {len(list(q))}." + document_reference_gid = list(q)[0]['vertex']['gid'] + + # 1 hop + specimen = graph.match_label(document_reference_gid, 'Specimen') + assert specimen is not None, "Expected Specimen" + assert specimen['vertex']['gid'] == '60c67a06-ea2d-4d24-9249-418dc77a16a9', f"Expected 60c67a06-ea2d-4d24-9249-418dc77a16a9 but got {specimen}." + + # 2 hops + patient = graph.match_label(document_reference_gid, 'Patient') + assert patient is not None, "Expected Patient" + assert patient['vertex']['gid'] == 'bc4e1aa6-cb52-40e9-8f20-594d9c84f920', f"Expected bc4e1aa6-cb52-40e9-8f20-594d9c84f920 but got {patient}." + + # 4 hops + research_study = graph.match_label(document_reference_gid, 'ResearchStudy') + assert research_study is not None, "Expected ResearchStudy" + assert research_study['vertex']['gid'] == '7dacd4d0-3c8e-470b-bf61-103891627d45', f"Expected 7dacd4d0-3c8e-470b-bf61-103891627d45 but got {research_study}." + + # Observations + q = graph.V(document_reference_gid).in_(["focus", "subject"]).hasLabel("Observation") + assert len(list(q)) == 2, f"Expected 2 but got {len(list(q))} for {document_reference_gid}." + + +def test_dataframe_associations(graph, expected_vertices, expected_dataframe_associations): + """Test the dataframe associations.""" + + actual_dataframe_associations = defaultdict(list) + # for all objects in the graph except Observations, retrieve the associated objects useful for a dataframe + for vertex_gid, vertex_label in expected_vertices: + if vertex_label == 'Observation': + continue + df = graph.dataframe_associations(vertex_gid, vertex_label) + actual_dataframe_associations[(vertex_label, vertex_gid)] = [(_['resourceType'], _['id']) for _ in df] + assert actual_dataframe_associations == expected_dataframe_associations, f"Expected {expected_dataframe_associations} but got {actual_dataframe_associations}." diff --git a/test/pygrip_test/test_pygrip.py b/test/pygrip_test/test_pygrip.py new file mode 100644 index 00000000..a21f881d --- /dev/null +++ b/test/pygrip_test/test_pygrip.py @@ -0,0 +1,29 @@ + +import pygrip +import unittest + +class TestPyGRIP(unittest.TestCase): + + def test_query(self): + + w = pygrip.NewMemServer() + + w.addVertex("1", "Person", {"age":30, "eyes":"brown"}) + w.addVertex("2", "Person", {"age":40, "eyes":"blue"}) + w.addEdge("1", "2", "knows") + + count = 0 + for row in w.V().hasLabel("Person"): + count += 1 + self.assertEqual(count, 2) + + count = 0 + for row in w.V().out("knows"): + count += 1 + self.assertEqual(count, 1) + + for row in w.V().count(): + self.assertEqual(row["count"], 2) + +if __name__ == '__main__': + unittest.main()