JSON to BSON conversion for testing purposes - testing

I'm writing a BSONDocumentReader and would like to create a BSONDocument from a JSON string in my test to verify whether it correctly builds the CC.
So far I haven't found an easy way to do so, can anyone provide an example?

Eventually I found the solution on SO, see this answer
import reactivemongo.play.json._
import play.modules.reactivemongo.json.collection._
val googleJs: JsObject = Json.parse(google).as[JsObject]
val googleBson: BSONDocument = BSONFormats.toBSON(googleJs).get.asInstanceOf[BSONDocument]
val maybeAddress = AddressReader read googleBson
maybeAddress shouldBe defined
// ... and so on...
Just make sure you have the play2-reactivemongo dependency

Related

Server side validation library for Kotlin

Can anyone please suggest me good server side validation library for kotlin.
Which can perform basic validation like below
Checking for spaces and new line in a string
Checking the minimum and maximum of character in a string
Checking empty string
As I need to use a validation library instead of below code
val data.name = "test test"
val nameMaxLimit: Int = 256
if (data.name.contains(" ") || data.name.isNullOrEmpty() || data.name.length > nameMaxLimit) {
return true
}
My project is a Gradle Project, So gradle supported validation library will be blessed
You can use beans validation. I think it is the best way.
You would need to annotate each field with the rules you want.
Then you would tell the validations to run.
It would return to you an array of violations.
Here an example:
import javax.validation.Validator
val violations = validator.validate(data)
if (violations.isEmpty()) {
successAction()
}

Micronaut declarative client with base url per environment

I'd like to be able to use Micronaut's declarative client to hit an a different endpoint based on whether I'm in a local development environment vs a production environment.
I'm setting my client's base uri in application.dev.yml:
myserviceclient:
baseUri: http://localhost:1080/endpoint
Reading the docs from Micronaut, they have the developer jumping through quite a few hoops to get a dynamic value piped into the actual client. They're actually quite confusing. So I've created a configuration like this:
#ConfigurationProperties(PREFIX)
class MyServiceClientConfig {
companion object {
const val PREFIX = "myserviceclient"
const val BASE_URL = "http://localhost:1080/endpoint"
}
var baseUri: String? = null
fun toMap(): MutableMap<String, Any> {
val m = HashMap<String, Any>()
if (baseUri != null) {
m["baseUri"] = baseUri!!
}
return m
}
}
But as you can see, that's not actually reading any values from application.yml, it's simply setting a const value as a static on the class. I'd like that BASE_URL value to be dynamic based on which environment I'm in.
To use this class, I've created a declarative client like this:
#Client(MyServiceClientConfig.BASE_URL)
interface MyServiceClient {
#Post("/user/kfc")
#Produces("application/json")
fun sendUserKfc(transactionDto: TransactionDto)
}
The docs show an example where they're interpolating values from the config map that's built like this:
#Get("/api/\${bintray.apiversion}/repos/\${bintray.organization}/\${bintray.repository}/packages")
But how would I make this work in the #Client() annotation?
Nowhere in that example do they show how bintray is getting defined/injected/etc. This appears to be the same syntax that's used with the #Value() annotation. I've tried using that as well, but every value I try to use ends up being null.
This is very frustrating, but I'm sure I'm missing a key piece that will make this all work.
I'm setting my client's base uri in application.dev.yml
You probably want application-dev.yml.
But how would I make this work in the #Client() annotation?
You can put a config key in the #Client value using something like #Client("${myserviceclient.baseUri}").
If you want the url somewhere in your code use this:
#Value("${micronaut.http.services.occupancy.urls}")
private String occupancyUrl;

KotlinPoet - Generate Koin module

I'm new to KotlinPoet and I cannot find how to create the following Koin module statement:
internal val apiModules = module {
single<Name1> { get<Retrofit>().create(Name1::class.java) }
single<Name2> { get<Retrofit>().create(Name2::class.java) }
}
directly into a Kotlin file (no wrapper class)
I have been playing around with PropertySpec and CodeBlock but I don't know how to import Koin DSL or how to reference those imported classes in the code generation. I was also unable to generate the code by pure string generation.
You need to generate the file using FileSpec and add a PropertySpec for the module
It shold look similar to this
val moduleClassName = ClassName("org.koin.core.module.Module", "Module") //This will take care of the import
val moduleMemberName = MemberName("org.koin.dsl.module", "module") //This will take care of the import
val moduleInitilizerCodeBlock =
CodeBlock.Builder()
.beginControlFlow("%M", moduleMemberName) //This will take care of the {} and indentations
.addStatment(ADD ANOTHER CODE BLOCK SIMNILAR TO THIS FOR THE SINGLE/FACTORY)
.endControlFlow()
.build()
val module = PropertySpec.builder("YOUR MODULE NAME", moduleClassName)
.initializer(moduleInitilizerCodeBlock)
.build()
FileSpec.Builder("FILE PACKAGE", "FILE NAME")
.addProperty(module)
.build()
This is not full code but it should point you in the right direction.
Side note: I might me wrong about specific namings but again it should be enough

How to update Resource value in ReadyAPI/SoapUI dynamically by groovy?

my resource is in this format "testing/101/getCustomer/99"
Here I need to change "101" and "99" part dynamically by groovy so that I can run for multiple values in same test case. I looked into the ReadyAPI's built in feature, but it was not that helpful.
I also found this link, but it changed the resource in the entire project. The solution I am looking for is in test case level. As my each test case will have different url.
https://community.smartbear.com/t5/SoapUI-Open-Source/How-to-set-the-resource-path-at-run-time-while...
Any help will be appreciated.
Here is what I have tried so far
import com.eviware.soapui.impl.rest.RestResource
import java.io.*;
def project = testRunner.testCase.testSuite.getProject()
String restServiceName = "Resource name" (From the Rest Request Properties)
List<RestResource> ops = project.getInterfaces()[restServiceName].getOperationList()
log.info("ops ::"+ops);
log.info("ops size ::"+ops.size());
for (RestResource restResource : ops) {
String pathStr = restResource.getFullPath();
log.info("pathStr first-->"+restResource.getFullPath());
restResource.setPath("testing/101/getCustomer/99");
if (pathStr.contains("101"))
{
restResource.setPath("testing/101/getCustomer/99");
restResource.setPath(pathStr.replace("testing/101/getCustomer/99", "testing/50/getCustomer/99"));
}
}
you could use a testCase level property
first set the the value of res by groovy like below
def x=101
def y=99
def res="testing/$x/getCustomer/$y"
testRunner.testCase.setPropertyValue("resourc",res)
Now the testcase level property is set. It can be used as below wherever you want
${#TestCase#res}

Google diff-match-patch : How to unpatch to get Original String?

I am using Google diff-match-patch JAVA plugin to create patch between two JSON strings and storing the patch to database.
diff_match_patch dmp = new diff_match_patch();
LinkedList<Patch> diffs = dmp.patch_make(latestString, originalString);
String patch = dmp.patch_toText(diffs); // Store patch to DB
Now is there any way to use this patch to re-create the originalString by passing the latestString?
I google about this and found this very old comment # Google diff-match-patch Wiki saying,
Unpatching can be done by just looping through the diff, swapping
DIFF_INSERT with DIFF_DELETE, then applying the patch.
But i did not find any useful code that demonstrates this. How could i achieve this with my existing code ? Any pointers or code reference would be appreciated.
Edit:
The problem i am facing is, in the front-end i am showing a revisions module that shows all the transactions of a particular fragment (take for example an employee details), like which user has updated what details etc. Now i am recreating the fragment JSON by reverse applying each patch to get the current transaction data and show it as a table (using http://marianoguerra.github.io/json.human.js/). But some JSON data are not valid JSON and I am getting JSON.parse error.
I was looking to do something similar (in C#) and what is working for me with a relatively simple object is the patch_apply method. This use case seems somewhat missing from the documentation, so I'm answering here. Code is C# but the API is cross language:
static void Main(string[] args)
{
var dmp = new diff_match_patch();
string v1 = "My Json Object;
string v2 = "My Mutated Json Object"
var v2ToV1Patch = dmp.patch_make(v2, v1);
var v2ToV1PatchText = dmp.patch_toText(v2ToV1Patch); // Persist text to db
string v3 = "Latest version of JSON object;
var v3ToV2Patch = dmp.patch_make(v3, v2);
var v3ToV2PatchTxt = dmp.patch_toText(v3ToV2Patch); // Persist text to db
// Time to re-hydrate the objects
var altV3ToV2Patch = dmp.patch_fromText(v3ToV2PatchTxt);
var altV2 = dmp.patch_apply(altV3ToV2Patch, v3)[0].ToString(); // .get(0) in Java I think
var altV2ToV1Patch = dmp.patch_fromText(v2ToV1PatchText);
var altV1 = dmp.patch_apply(altV2ToV1Patch, altV2)[0].ToString();
}
I am attempting to retrofit this as an audit log, where previously the entire JSON object was saved. As the audited objects have become more complex the storage requirements have increased dramatically. I haven't yet applied this to the complex large objects, but it is possible to check if the patch was successful by checking the second object in the array returned by the patch_apply method. This is an array of boolean values, all of which should be true if the patch worked correctly. You could write some code to check this, which would help check if the object can be successfully re-hydrated from the JSON rather than just getting a parsing error. My prototype C# method looks like this:
private static bool ValidatePatch(object[] patchResult, out string patchedString)
{
patchedString = patchResult[0] as string;
var successArray = patchResult[1] as bool[];
foreach (var b in successArray)
{
if (!b)
return false;
}
return true;
}