Add docs examples as driver tests (#29)

This commit is contained in:
Marko Budiselić 2020-10-23 18:02:33 +02:00 committed by GitHub
parent 126c9d697b
commit 92bad4f62b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 274 additions and 165 deletions

View File

@ -11,8 +11,11 @@ java/**/*.class
java/**/*.jar
# javascript driver
javascript/**/node_modules
javascript/**/package-lock.json
javascript/websockify-js/
# node driver
node/**/node_modules
node/**/package-lock.json
# python driver
python/ve3

View File

@ -1,20 +0,0 @@
using System;
using System.Linq;
using Neo4j.Driver;
public class Basic {
public static void Main(string[] args) {
using(var driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.None, (ConfigBuilder builder) => builder.WithEncryptionLevel(EncryptionLevel.None)))
using(var session = driver.Session())
{
session.Run("MATCH (n) DETACH DELETE n").Consume();
session.Run("CREATE (alice:Person {name: \"Alice\", age: 22})").Consume();
var result = session.Run("MATCH (n) RETURN n").First();
var alice = (INode) result["n"];
Console.WriteLine(alice["name"]);
Console.WriteLine(string.Join(", ", alice.Labels));
Console.WriteLine(alice["age"]);
}
Console.WriteLine("All ok!");
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Linq;
using Neo4j.Driver;
public class Basic {
public static void Main(string[] args) {
using(var driver = GraphDatabase.Driver(
"bolt://localhost:7687", AuthTokens.None,
(ConfigBuilder builder) => builder.WithEncryptionLevel(EncryptionLevel.None)))
using(var session = driver.Session())
{
session.Run("MATCH (n) DETACH DELETE n;").Consume();
Console.WriteLine("Database cleared.");
session.Run("CREATE (alice:Person {name: \"Alice\", age: 22});").Consume();
Console.WriteLine("Record created.");
var node = (INode) session.Run("MATCH (n) RETURN n;").First()["n"];
Console.WriteLine("Record matched.");
var label = string.Join("", node.Labels);
var name = node["name"];
var age = (long) node["age"];
if (!label.Equals("Person") || !name.Equals("Alice") || !age.Equals(22)) {
Console.WriteLine("Data doesn't match!");
System.Environment.Exit(1);
}
Console.WriteLine("Label: " + label);
Console.WriteLine("name: " + name);
Console.WriteLine("age: " + age);
}
Console.WriteLine("All ok!");
}
}

View File

@ -12,9 +12,9 @@ for i in dotnet; do
done
for i in *; do
if [ ! -d $i ]; then
if [ ! -d $i ]; then
continue
fi
fi
pushd $i
dotnet publish -c release --self-contained --runtime linux-x64 --framework netcoreapp2.1 -o build/
./build/$i

View File

@ -1,67 +0,0 @@
package main
import "github.com/neo4j/neo4j-go-driver/neo4j"
import "fmt"
import "log"
func handle_error(err error) {
log.Fatal("Error occured: %s", err)
}
func main() {
configForNeo4j40 := func(conf *neo4j.Config) { conf.Encrypted = false }
driver, err := neo4j.NewDriver("bolt://localhost:7687", neo4j.BasicAuth("", "", ""), configForNeo4j40)
if err != nil {
log.Fatal("An error occurred opening conn: %s", err)
}
defer driver.Close()
sessionConfig := neo4j.SessionConfig{AccessMode: neo4j.AccessModeWrite}
session, err := driver.NewSession(sessionConfig)
if err != nil {
log.Fatal("An error occured while creating a session: %s", err)
}
defer session.Close()
result, err := session.Run("MATCH (n) DETACH DELETE n", map[string]interface{}{})
if err != nil {
handle_error(err)
}
_, err = result.Consume()
if err != nil {
handle_error(err)
}
result, err = session.Run(`CREATE (alice:Person {name: "Alice", age: 22})`, map[string]interface{}{})
if err != nil {
handle_error(err)
}
_, err = result.Consume()
if err != nil {
handle_error(err)
}
result, err = session.Run("MATCH (n) RETURN n", map[string]interface{}{})
if err != nil {
handle_error(err)
}
if !result.Next() {
log.Fatal("Missing result")
}
node_record, has_column := result.Record().Get("n")
if !has_column {
log.Fatal("Wrong result returned")
}
node_value := node_record.(neo4j.Node)
fmt.Println(node_value.Props()["name"])
fmt.Println(node_value.Labels())
fmt.Println(node_value.Props()["age"])
fmt.Println("All ok!")
}

View File

@ -0,0 +1,69 @@
package main
import "github.com/neo4j/neo4j-go-driver/neo4j"
import "fmt"
import "log"
func handle_if_error(err error) {
if err != nil {
log.Fatal("Error occured: %s", err)
}
}
func main() {
configForNeo4j40 := func(conf *neo4j.Config) { conf.Encrypted = false }
driver, err := neo4j.NewDriver("bolt://localhost:7687",
neo4j.BasicAuth("", "", ""),
configForNeo4j40)
if err != nil {
log.Fatal("An error occurred opening conn: %s", err)
}
defer driver.Close()
sessionConfig := neo4j.SessionConfig{AccessMode: neo4j.AccessModeWrite}
session, err := driver.NewSession(sessionConfig)
if err != nil {
log.Fatal("An error occured while creating a session: %s", err)
}
defer session.Close()
result, err := session.Run("MATCH (n) DETACH DELETE n;",
map[string]interface{}{})
handle_if_error(err)
_, err = result.Consume()
handle_if_error(err)
fmt.Println("Database cleared.")
result, err = session.Run(`CREATE (alice:Person {name: "Alice", age: 22});`,
map[string]interface{}{})
handle_if_error(err)
_, err = result.Consume()
handle_if_error(err)
fmt.Println("Record created.")
result, err = session.Run("MATCH (n) RETURN n;", map[string]interface{}{})
handle_if_error(err)
if !result.Next() {
log.Fatal("Missing result.")
}
node_record, has_column := result.Record().Get("n")
if !has_column {
log.Fatal("Wrong result returned.")
}
node_value := node_record.(neo4j.Node)
fmt.Println("Record matched.")
label := node_value.Labels()[0]
name := node_value.Props()["name"]
age := node_value.Props()["age"]
if label != "Person" && name != "Alice" && age != 22 {
log.Fatal("Data doesn't match.")
}
fmt.Println("Label", label)
fmt.Println("name", name)
fmt.Println("age", age)
fmt.Println("All ok!")
}

View File

@ -10,5 +10,5 @@ done
go get github.com/neo4j/neo4j-go-driver/neo4j
go run basic.go
go run docs_how_to_query.go
go run transactions.go

View File

@ -1,38 +0,0 @@
import org.neo4j.driver.*;
import org.neo4j.driver.types.*;
import static org.neo4j.driver.Values.parameters;
import java.util.*;
public class Basic {
public static void main(String[] args) {
Config config = Config.builder().withoutEncryption().build();
Driver driver = GraphDatabase.driver( "bolt://localhost:7687", AuthTokens.basic( "neo4j", "1234" ), config );
try ( Session session = driver.session() ) {
Result rs1 = session.run( "MATCH (n) DETACH DELETE n" );
System.out.println( "Database cleared." );
Result rs2 = session.run( "CREATE (alice: Person {name: 'Alice', age: 22})" );
System.out.println( "Record created." );
Result rs3 = session.run( "MATCH (n) RETURN n" );
System.out.println( "Record matched." );
List<Record> records = rs3.list();
Record record = records.get( 0 );
Node node = record.get( "n" ).asNode();
if ( !node.get("name").asString().equals( "Alice" ) || node.get("age").asInt() != 22 ) {
System.out.println( "Data doesn't match!" );
System.exit( 1 );
}
System.out.println( "All ok!" );
}
catch ( Exception e ) {
System.out.println( e );
System.exit( 1 );
}
driver.close();
}
}

View File

@ -0,0 +1,40 @@
import java.util.*;
import org.neo4j.driver.*;
public class DocsHowToQuery {
public static void main(String[] args) {
var config = Config.builder().withoutEncryption().build();
var driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("", ""), config);
try (var session = driver.session()) {
session.run("MATCH (n) DETACH DELETE n;");
System.out.println("Database cleared.");
session.run("CREATE (alice:Person {name: 'Alice', age: 22});");
System.out.println("Record created.");
var node = session.run("MATCH (n) RETURN n;").list().get(0).get("n").asNode();
System.out.println("Record matched.");
var label = node.labels().iterator().next();
var name = node.get("name").asString();
var age = node.get("age").asInt();
if (!label.equals("Person") || !name.equals("Alice") || age != 22) {
System.out.println("Data doesn't match!");
System.exit(1);
}
System.out.println("Label: " + label);
System.out.println("name: " + name);
System.out.println("age: " + age);
System.out.println("All ok!");
} catch (Exception e) {
System.out.println(e);
System.exit(1);
}
driver.close();
}
}

View File

@ -22,11 +22,11 @@ if [ ! -f $REACTIVE_STREAM_DEP ]; then
wget -nv https://repo1.maven.org/maven2/org/reactivestreams/reactive-streams/1.0.3/reactive-streams-1.0.3.jar -O $REACTIVE_STREAM_DEP || exit 1
fi
javac -classpath .:$DRIVER:$REACTIVE_STREAM_DEP Basic.java
java -classpath .:$DRIVER:$REACTIVE_STREAM_DEP Basic
javac -classpath .:$DRIVER:$REACTIVE_STREAM_DEP DocsHowToQuery.java
java -classpath .:$DRIVER:$REACTIVE_STREAM_DEP DocsHowToQuery
javac -classpath .:$DRIVER:$REACTIVE_STREAM_DEP MaxQueryLength.java
java -classpath .:$DRIVER:$REACTIVE_STREAM_DEP MaxQueryLength
javac -classpath .:$DRIVER:$REACTIVE_STREAM_DEP Transactions.java
java -classpath .:$DRIVER:$REACTIVE_STREAM_DEP Transactions
java -classpath .:$DRIVER:$REACTIVE_STREAM_DEP Transactions

View File

@ -0,0 +1,11 @@
# JavaScript Example
This example is publicly available [here](
https://docs.memgraph.com/memgraph/how-to-guides-overview/query-memgraph-programmatically#javascript-example).
It's NOT automatically executed within the CI system because setting up the
environment to executed and test JavaScript from HTML is too much effort for
too little gain. It's possible to open HTML and test the functionality
manually.
IMPORTANT: `setup.sh` + `docs_how_to_query.html` and relevant docs page have
to be in sync.

View File

@ -0,0 +1,50 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Javascript Browser Example | Memgraph</title>
<script src="https://cdn.jsdelivr.net/npm/neo4j-driver"></script>
</head>
<body>
<p>Check console for Cypher query outputs...</p>
<script>
const driver = neo4j.driver(
"bolt://localhost:9999",
neo4j.auth.basic("", ""),
);
(async function main() {
const session = driver.session();
try {
await session.run("MATCH (n) DETACH DELETE n;");
console.log("Database cleared.");
await session.run("CREATE (alice:Person {name: 'Alice', age: 22});");
console.log("Record created.");
const result = await session.run("MATCH (n) RETURN n;");
console.log("Record matched.");
const alice = result.records[0].get("n");
const label = alice.labels[0]
const name = alice.properties["name"];
const age = alice.properties["age"];
if (label != "Person" || name != "Alice" || age != 22) {
console.error("Data doesn't match.");
}
console.log("Label: " + label);
console.log("name: " + name);
console.log("age: " + age);
} catch (error) {
console.error(error);
} finally {
session.close();
}
driver.close();
})();
</script>
</body>
</html>

View File

@ -0,0 +1,8 @@
#!/bin/bash
if [ ! -d "websockify-js" ]; then
git clone https://github.com/novnc/websockify-js.git
fi
cd websockify-js/websockify
npm install
./websockify.js 9999 :7687

View File

@ -1,6 +1,6 @@
var neo4j = require('neo4j-driver');
var driver = neo4j.driver("bolt://localhost:7687",
neo4j.auth.basic("neo4j", "1234"),
neo4j.auth.basic("", ""),
{ encrypted: 'ENCRYPTION_OFF' });
var session = driver.session();
@ -18,17 +18,23 @@ function run_query(query, callback) {
});
}
run_query("MATCH (n) DETACH DELETE n", function (result) {
run_query("MATCH (n) DETACH DELETE n;", function (result) {
console.log("Database cleared.");
run_query("CREATE (alice: Person {name: 'Alice', age: 22})", function (result) {
run_query("CREATE (alice:Person {name: 'Alice', age: 22});", function (result) {
console.log("Record created.");
run_query("MATCH (n) RETURN n", function (result) {
console.log("Record matched.");
var alice = result.records[0].get("n");
if(alice.labels[0] != "Person" || alice.properties["name"] != "Alice"){
const alice = result.records[0].get("n");
const label = alice.labels[0];
const name = alice.properties["name"];
const age = alice.properties["age"];
if(label != "Person" || name != "Alice" || age != 22){
console.log("Data doesn't match!");
die();
}
console.log("Label: " + label);
console.log("name: " + name);
console.log("age: " + age);
console.log("All ok!");
driver.close();
});

View File

@ -13,5 +13,5 @@ if [ ! -d node_modules ]; then
npm install neo4j-driver
fi
node basic.js
node docs_how_to_query.js
node max_query_length.js

View File

@ -1,25 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from neo4j import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost:7687",
auth=basic_auth("", ""),
encrypted=False)
session = driver.session()
session.run('MATCH (n) DETACH DELETE n').consume()
session.run('CREATE (alice:Person {name: "Alice", age: 22})').consume()
returned_result_set = session.run('MATCH (n) RETURN n')
returned_result = returned_result_set.single()
alice = returned_result["n"]
print(alice['name'])
print(set(alice.labels))
print(alice['age'])
session.close()
driver.close()
print("All ok!")

View File

@ -0,0 +1,36 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from neo4j import GraphDatabase, basic_auth
driver = GraphDatabase.driver('bolt://localhost:7687',
auth=basic_auth('', ''),
encrypted=False)
session = driver.session()
session.run('MATCH (n) DETACH DELETE n').consume()
print('Database cleared.')
session.run('CREATE (alice:Person {name: "Alice", age: 22})').consume()
print('Record created.')
node = session.run('MATCH (n) RETURN n').single()['n']
print('Record matched.')
label = list(node.labels)[0]
name = node['name']
age = node['age']
if label != 'Person' or name != 'Alice' or age != 22:
print('Data does not match')
sys.exit(1)
print('Label: %s' % label)
print('name: %s' % name)
print('age: %s' % age)
session.close()
driver.close()
print('All ok!')

View File

@ -28,6 +28,6 @@ fi
source ve3/bin/activate
# execute test
python3 basic.py || exit 1
python3 docs_how_to_query.py || exit 1
python3 max_query_length.py || exit 1
python3 transactions.py || exit 1