@Test
public void test() {
int userId = Math.abs(new Random().nextInt() % 10) + 1
HTTPResponse response = request.GET("http://127.0.0.1:8030/feed-server/feed/" + {userId} + "?last_post_id=63ef9fdd81f9764fdd5ba0ce", params)
if (response.statusCode == 301 || response.statusCode == 302) {
grinder.logger.warn("Warning. The response may not be correct. The response code was {}.", response.statusCode)
} else {
assertThat(response.statusCode, is(200))
}
}
The above code is part of the test code script written in groovy.
The userId is randomly imported for accurate testing.
I want to write the last_post_id to be imported randomly like userId.
However, the last_post_id is MongoDB's _id, so it is not a continuous value like userId.
The method I thought about proceeds in the following order.
Get all the _id from MongoDB and put it in an array.
Choose random from the values in the array.
Below is the complete source code written in groovy.
import static net.grinder.script.Grinder.grinder
import static org.junit.Assert.*
import static org.hamcrest.Matchers.*
import net.grinder.script.GTest
import net.grinder.script.Grinder
import net.grinder.scriptengine.groovy.junit.GrinderRunner
import net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess
import net.grinder.scriptengine.groovy.junit.annotation.BeforeThread
// import static net.grinder.util.GrinderUtils.* // You can use this if you're using nGrinder after 3.2.3
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import org.ngrinder.http.HTTPRequest
import org.ngrinder.http.HTTPRequestControl
import org.ngrinder.http.HTTPResponse
import org.ngrinder.http.cookie.Cookie
import org.ngrinder.http.cookie.CookieManager
@Grapes([
@Grab(group='org.mongodb', module='mongo-java-driver', version='3.12.12')
])
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
/**
* A simple example using the HTTP plugin that shows the retrieval of a single page via HTTP.
*
* This script is automatically generated by ngrinder.
*
* @author admin
*/
@RunWith(GrinderRunner)
class TestRunner {
public static GTest test
public static HTTPRequest request
public static Map<String, String> headers = [:]
public static Map<String, Object> params = [:]
public static List<Cookie> cookies = []
public static List<String> last_post_ids = []
public static final String db_name = "instaclone_post"
public static final String collection_name = "post"
@BeforeProcess
public static void beforeProcess() {
HTTPRequestControl.setConnectionTimeout(300000)
test = new GTest(1, "127.0.0.1")
request = new HTTPRequest()
grinder.logger.info("before process.")
}
@BeforeThread
public void beforeThread() {
test.record(this, "test")
grinder.statistics.delayReports = true
grinder.logger.info("before thread.")
}
@Before
public void before() {
request.setHeaders(headers)
CookieManager.addCookies(cookies)
grinder.logger.info("before. init headers and cookies")
def mongoClient = MongoClients.create("mongodb://localhost:27017")
grinder.logger.info("before. create MongoClients")
def collection = mongoClient.getDatabase(db_name).getCollection(collection_name)
def documents = collection.find(new Document(), new Document("_id", 1)).into([])
for (document in documents) {
println(document.get("_id"))
last_post_ids.add(document.get("_id"))
}
}
@Test
public void test() {
int userId = Math.abs(new Random().nextInt() % 10) + 1
Random rand = new Random();
HTTPResponse response = request.GET("http://127.0.0.1:8030/feed-server/feed/" + {userId} + "?last_post_id=" + last_post_ids.nextInt(5), params)
if (response.statusCode == 301 || response.statusCode == 302) {
grinder.logger.warn("Warning. The response may not be correct. The response code was {}.", response.statusCode)
} else {
assertThat(response.statusCode, is(200))
}
}
}
The following error appears.
The following error appears.
unable to resolve class com.mongodb.MongoClient
@ line 22, column 1.
@Grapes([
^
unable to resolve class com.mongodb.client.MongoCollection
@ line 26, column 1.
import com.mongodb.client.MongoCollection;
^
unable to resolve class com.mongodb.client.MongoCursor
@ line 27, column 1.
import com.mongodb.client.MongoCursor;
^
unable to resolve class org.bson.Document
@ line 28, column 1.
import org.bson.Document;
^
unable to resolve class HTTPRequest
@ line 60, column 2.
public static HTTPRequest request
^
unable to resolve class Cookie
@ line 63, column 21.
public static List<Cookie> cookies = []
^
unable to resolve class HTTPRequest
@ line 72, column 13.
request = new HTTPRequest()
^
HTTPResponse response = request.GET("http://127.0.0.1:8030/feed-server/feed/" + {userId} + "?last_post_id=" + last_post_ids.nextInt(5), params)
^
8 errors
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:295)
at org.codehaus.groovy.control.CompilationUnit$ISourceUnitOperation.doPhaseOperation(CompilationUnit.java:914)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:627)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:389)
at groovy.lang.GroovyClassLoader.lambda$parseClass$3(GroovyClassLoader.java:332)
at org.codehaus.groovy.runtime.memoize.StampedCommonCache.compute(StampedCommonCache.java:163)
at org.codehaus.groovy.runtime.memoize.StampedCommonCache.getAndPut(StampedCommonCache.java:154)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:330)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:314)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:244)
at net.grinder.scriptengine.groovy.GroovyScriptEngine.<init>(GroovyScriptEngine.java:64)
I tried using ChatGPT to solve this problem and I couldn't solve it even if I modified the script more than 50 times.
There is not much data to refer to.
So it looks like your groovy is being compiled so you want those classes in your classloader during compilation (which seems like its practically the first thing Groovy does). Try adding this to your groovy command line parameters
-Dgroovy.grape.report.downloads=true. That will print out the download report so you can see if your Grapes are being seen or not. If that's not enough you can step it up with this-Divy.message.logger.level=4that will log what ivy is doing to retrieve your grapes.I see you have Mongo defined, but not Grinder, JUnit, or Hamcrest so I'm not sure if those classes are going to be there for you or not. If Grinder or Junit is doing something with classloaders (ie making new classloaders for your code) you might have problems seeing things. You can change how the Mongo driver is loaded by putting it on the system classloader like so:
You may also want to move the
@Grapesdown onto your class instead of in the import statements. Like so:That way you know it can see the annotation.