I am trying neo4j plugin and I created a simple test as follows:
package com.iibs.graph
import groovy.util.GroovyTestCase
import com.iibs.graph.Node
public class NodeTests extends GroovyTestCase {
void testCRUD() {
Node.deleteAll(Node.list())
Node node = new Node(name: "Name")
node.save(flush: true, failOnError: true)
Node found = Node.findByName("Name")
assert found instanceof Node
assert found.getName() == "Name"
assert found.node instanceof org.neo4j.graphdb.Node
}
}
Based on the documentation: http://projects.spring.io/grails-data-mapping/neo4j/manual/ref/Additional%20Gorm%20Methods/getNode.html
this test is expected to pass without any problems, however I am getting the following error:
| Failure: testCRUD(com.iibs.graph.NodeTests)
| Assertion failed:
assert found.node instanceof org.neo4j.graphdb.Node
| | |
| null false
com.iibs.graph.Node(Name)
at com.iibs.graph.NodeTests.testCRUD(NodeTests.groovy:20)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
| Completed 1 integration test, 1 failed in 0m 1s
Am I using the API in a wrong way?
Also, if I changing the last assertion line to:
assert found.getNode() instanceof org.neo4j.graphdb.Node
The error is different:
Failure: testCRUD(com.iibs.graph.NodeTests)
| groovy.lang.MissingMethodException: No signature of method: com.iibs.graph.Node.getNode() is applicable for argument types: () values: []
Possible solutions: getName(), getId(), setName(java.lang.String), getMongo(), getAll(), getCount()
at com.iibs.graph.NodeTests.testCRUD(NodeTests.groovy:20)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
| Completed 1 integration test, 1 failed in 0m 2s
As shown in the error, one of the proposed solutions is to use getMongo. What does it have to do with mongo. Here is my entity:
package com.iibs.graph
import groovy.transform.ToString;
#ToString(includes='name')
class Node {
String name
static mapWith = "neo4j"
static constraints = {
}
}
Thanks,
The docs for the plugin have not yet been updated for 2.x - it's the first milestone.
In short, domain instances no longer have a node property since we're relying on Cypher internally only. The id property of the domain instance refers to the __id__ property on the node in the graph.
Related
I am creating a Jira software server plugin for v7.13.0. I am creating an API to get all the issue security levels of a user.
My code for the same is as follows:
UserManager userManager = ComponentAccessor.getComponentOfType(UserManager.class);
#GET
#Produces({MediaType.APPLICATION_JSON})
#Path("user-security-levels")
public Response getUserSecurityLevels(#QueryParam("user") String user) {
log.error("entering getSecurityLevels function");
log.error("name of the user: " + user);
ApplicationUser targetUser = userManager.getUserByName(user);
log.error("value of targetUser: " + targetUser);
IssueSecurityLevelManager issueSecurityLevelManager = ComponentAccessor.getComponentOfType(IssueSecurityLevelManager.class);
Collection<IssueSecurityLevel> securityLevelsOfUser = issueSecurityLevelManager.getAllSecurityLevelsForUser(targetUser);
log.error("user security levels: " + securityLevelsOfUser);
return securityLevelsOfUser == null ? Response.status(Response.Status.NOT_FOUND)
.build() : Response.ok(securityLevelsOfUser).build();
}
But, this code is not working and is giving the following error:
2022-10-27 16:00:35,623 http-nio-8080-exec-13 ERROR [o.a.c.c.C.[.[localhost].[/].[default]] Servlet.service() for servlet [default] in context with path [] threw exception
org.codehaus.jackson.map.JsonMappingException: No serializer found for class com.atlassian.jira.issue.security.IssueSecurityLevelImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: java.util.HashSet[0])
I'm just getting started with Playwright so I don't know if there is something I'm missing. I do not have any other testing framework wired up to it. I'm using #playwright/test v1.14.1.
This test:
import { test, expect } from "#playwright/test";
test("focus sets tab indexes appropriately", async ({ page }) => {
await page.goto("http://localhost:3000/test");
const inputs = page.locator("input");
await expect(inputs).toHaveCount(5);
await inputs.evaluateAll(async (nodes) => {
console.log(nodes);
for (const node of nodes) {
console.log(node);
await expect(node.tabIndex).toBe(0);
}
});
});
is producing the following error:
locator.evaluateAll: Evaluation failed: ReferenceError: _test is not defined
at eval (eval at evaluate (:3:1339), <anonymous>:6:7)
at t.default.evaluate (<anonymous>:3:1362)
at t.default.<anonymous> (<anonymous>:1:44)
5 | const inputs = page.locator("input");
6 | await expect(inputs).toHaveCount(5);
> 7 | await inputs.evaluateAll(async (nodes) => {
| ^
8 | console.log(nodes);
9 | for (const node of nodes) {
10 | console.log(node);
If I remove the call to expect, the test passes but the console.log still will not fire off.
input.evaluateAll gets executed inside the browser which is a different execution context in which expect is not available (Node.js vs. e.g. Chromium).
See here: https://playwright.dev/docs/evaluating
I am using Grails 2.4.4 and want to apply spock tests in my project.
Below is the MemberService:
#Transactional
class MemberService {
def lastMember = null
def login (userId, password) {
def member = Member.findByLoginEmail(userId)
if(!member) return LoginResult.NO_SUCH_MEMBER
if (member.isLocked) return LoginResult.MEMBER_IS_LOCKED
log.debug("member.password is [${member.passwd}], input password is [${password}]")
if (!member.passwd.equals(password)) return LoginResult.PASSWORD_ERROR
switch(member.validateResult) {
case "FAILED":
return LoginResult.VAILDATE_FAILED
case "WAIT":
return LoginResult.WAIT_VALIDATE
}
member.lasLoginTime = new Timestamp(System.currentTimeMillis())
member.lastLoginPlatform = "WEB"
member.loginFailCount = 0
member.save()
lastMember = member
return LoginResult.SUCCESS
}
enum LoginResult {
SUCCESS,
NO_SUCH_MEMBER,
PASSWORD_ERROR,
MEMBER_IS_LOCKED,
VAILDATE_FAILED,
WAIT_VALIDATE
}
enum ValidateResult {
SUCCESS,
FAILED,
WAIT
}
}
MemberServiceSpec is as below:
#TestFor(MemberService)
#Mock(Member)
class MemberServiceSpec extends Specification {
def memberService
def setup() {
memberService = new MemberService()
}
void "test something"() {
when:
println "service is ${service}"
def result = memberService.login("aa#mymail.com", "123456")
println "result is ${result}"
then:
result == MemberService.LoginResult.SUCCESS
}
}
The test result is as below:
Testing started at 15:15 ...
|Loading Grails 2.4.4
|Configuring classpath
.
|Environment set to test
....................................
|Running without daemon...
..........................................
|Compiling 1 source files
.
|Running 2 unit tests...|Running 2 unit tests... 1 of 2
--Output from test something--
1. setup
service is cusine_market.MemberService#54c425b1
Enter MemberService.login----------------userId=[aa#mymail.com]
result is NO_SUCH_MEMBER
Failure: |
test something(cusine_market.MemberServiceSpec)
|
Condition not satisfied:
result == MemberService.LoginResult.SUCCESS
| |
| false
NO_SUCH_MEMBER
at cusine_market.MemberServiceSpec.test something(MemberServiceSpec.groovy:32)
Condition not satisfied:
result == MemberService.LoginResult.SUCCESS
| |
| false
NO_SUCH_MEMBER
Condition not satisfied:
result == MemberService.LoginResult.SUCCESS
| |
| false
NO_SUCH_MEMBER
at cusine_market.MemberServiceSpec.test something(MemberServiceSpec.groovy:32)
|Completed 1 unit test, 1 failed in 0m 6s
.Tests FAILED
I confirm that the user exists in database.
Could anyone tell me why MemberService can not find the user "aa#mymail.com" in database? I also tried the below line
memberService = Mock(MemberService);
The result is the same. However, if I run-app, the service does find the user.
Mocking
In your test you're testing MemberService, which means you don't need to mock it. Just refer to it via service.
Test Data
This looks like unit test, not the integration one. So it doesn't use your database at all.
What you need to do is to create the Member instance manually in test. You have it in your #Mock annotation, which is good.
Now, create the object, preferably in a given block:
void "test something"() {
given:
new Member(loginEmail: 'aa#mymail.com', password: '123456', ...).save(failOnError: true, flush: true)
when:
println "service is ${service}"
def result = service.login("aa#mymail.com", "123456")
println "result is ${result}"
then:
result == MemberService.LoginResult.SUCCESS
}
I added failOnError: true to make sure the object has actually been created. You - of course - need to provide all required properties in Member constructor and make sure the data you provide correspond to the one you provide to login method.
Also, you need to ensure the Member object is initialized in a way that fulfills the path you want to reach. For example, if you want to reach LoginResult.SUCCES state, you need to set member.isLocked to false, etc.
BONUS
When you get this test to work, you may want to take a look into Build Test Data Plugin. It makes creating test data - like your Member object - much easier.
as continuation of Trying out neo4j grails plugin, but it does not mach the docs
I have a test now looks like this:
package com.iibs.graph
import groovy.util.GroovyTestCase
import com.iibs.graph.Node
public class NodeTests extends GroovyTestCase {
def graphDatabaseService
void testCRUD() {
Node.deleteAll(Node.list())
Node node = new Node(name: "Name")
node.save(flush: true, failOnError: true)
Node found = Node.findByName("Name")
assert found instanceof Node
assert found.getName() == "Name"
org.neo4j.graphdb.Node graphNode = graphDatabaseService.getNodeById(node.getId())
assert graphNode.instanceOf(org.neo4j.graphdb.Node) == true
}
}
And I am getting an error as follows:
| Running 1 integration test... 1 of 1
| Failure: testCRUD(com.iibs.graph.NodeTests)
| org.neo4j.graphdb.NotFoundException: Node 905482810884096 not found
at org.neo4j.kernel.InternalAbstractGraphDatabase.getNodeById(InternalAbstractGraphDatabase.java:1088)
at com.iibs.graph.NodeTests.testCRUD(NodeTests.groovy:22)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
| Completed 1 integration test, 1 failed in 0m 2s
As far as I understand from the mentioned thread, this should be one of the possible ways to get the node. Or am I wrong?
Try the following snippet (did not test myself, just a braindump):
def nodeInstance = ....
nodeInstance.save(flush:true)
String label = nodeInstance.getClass().simpleName
def neoNode = graphDatabaseService.findNodesByLabelAndProperty(DynamicLabel.label(label), "__id__", nodeInstance.id)
I've repeatedly had problems with the DSL introduced by Grails in version 1.1 for configuring Log4J. My current configuration looks like this:
log4j = {
debug 'com.mypackages'
appenders {
console name: 'stdout', layout: pattern(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %c{1} - %m%n')
rollingFile name: 'hibeFile', file: "hibeFile", maxFileSize: '500KB'
}
// By default, messages are logged at the error level to both the console and hibeFile
root {
error 'stdout', 'hibeFile'
additivity = true
}
}
The intention here is:
Log com.mypackages at the debug level and all others at the error level
Log all output to a file named hibeFile and the console
This works fine when I run the application or the integration tests. However, when I run the unit tests no logging appears either in the console, or in the "System.out" or "System.err" links shown in the Grails test report. How can I see my logs when running unit tests?
Thanks,
Don
AFAIK, when running a Grails unit test, the whole logging is not available via log4j, the log.xxxx calls in domain classes etc. are just mocked using
mockLogging(ClassUnderTest, true)
The "true" stands for "enable debug". In order to do so, the unit test class must extend GrailsUnitTestCase.
If you use mockController(class), it implicitly calls mockLogging(class, false) and therefore you get no debug logging. For details check out the grails sources, esp GrailsUnitTestCase and MockUtils.
In opposite to the above, in an integration test the whole machinery is started and log4j is available.
Here is a thought, you didn't ask this exactly but the same question was asked on the grails user group. I am posting my answer here as well, to spread the knowledge.
If you are explicitly saying def log = org.apache.commons.logging.LogFactory.getLog(this) in your classes rather than relying on dependency injection as was explained on the grails user group you can mock the getLog on the LogFactory.
The below is taken from grails.tests.MockUtils.mockLogging and modified to return the logger.
class LoggingEnabledTestCase extends GrailsUnitTestCase {
protected void setUp() {
super.setUp()
registerMetaClass(org.apache.commons.logging.LogFactory)
org.apache.commons.logging.LogFactory.metaClass.'static'.getLog = {instance ->
// This is taken from grails.tests.MockUtils and slightly changed to return a logger.
// Get the name of the class + the last component of the package
// (if it the class is in a package).
def pos = instance.class.name.lastIndexOf('.')
if (pos != -1) pos = instance.class.name.lastIndexOf('.', pos - 1)
def shortName = instance.class.name.substring(pos + 1)
// Dynamically inject a mock logger that simply prints the
// log message (and optional exception) to stdout.
def mockLogger = [
fatal: {String msg, Throwable t = null ->
println "FATAL (${shortName}): $msg"
if (t) {
println " Exception thrown - ${t.message}"
}
},
error: {String msg, Throwable t = null ->
println "ERROR (${shortName}): $msg"
if (t) {
println " Exception thrown - ${t.message}"
}
},
warn: {String msg, Throwable t = null ->
println "WARN (${shortName}): $msg"
if (t) {
println " Exception thrown - ${t.message}"
}
},
info: {String msg, Throwable t = null ->
println "INFO (${shortName}): $msg"
if (t) {
println " Exception thrown - ${t.message}"
}
},
debug: {String msg, Throwable t = null ->
println "DEBUG (${shortName}): $msg"
if (t) {
println " Exception thrown - ${t.message}"
}
},
trace: {String msg, Throwable t = null -> },
isFatalEnabled: {-> true},
isErrorEnabled: {-> true},
isWarnEnabled: {-> true},
isInfoEnabled: {-> true},
isDebugEnabled: {-> true},
isTraceEnabled: {-> false}] as Log
return mockLogger
}
}
protected void tearDown() {
super.tearDown()
}
}
Using Grails 1.1.1 and an approximation to your setup, I have a unit test called FooTests.groovy
After running grails test-app, I am able to see the output from the test in the directory:
./test/reports/plain
specifically in the files, as appropriate:
TEST-com.mypackages.FooTests-err.txt
TEST-com.mypackages.FooTests-out.txt
TEST-com.mypackages.FooTests.txt
Note that I see no output in the hibeFile. I'm not sure, but I suspect a previous poster is correct in that unit tests don't receive the logging setup.