Easy Mock issue with Blob - easymock

We are using Easy Mock for creating JUnit test case in java with H2 database.
As code of fetching the Blob content is specific to Oracle and getting the following error.
ClassCastException: Cannot cast org.h2.jdbc.JdbcResultSet (id=72) to oracle.jdbc.driver.OracleResultSet
public BLOB getBLOB(String field) throws SQLException {
try {return ((OracleResultSet) rs).getBLOB(field);
} catch (NullPointerException e) {}}
Bit stuck with this as how can we handle this in Easy Mock without changing the above code.

You are doing something weird here. If you are using EasyMock to mock the blob, you should mock OracleResultSet, not JdbcResultSet.
You don't need H2 here. Since you are mocking.
As a side note: Please remote the empty catch of the NPE. You are heavily shooting yourself in the foot when doing that.

We are not mocking JdbcResultSet.In this case we are fetching the blob contents from database so we can't mock OracleResultSet. Removed the code from Empty catch.

Related

Testing AppService: System.ObjectDisposedException

Using the abp.io module template
Using the sqlite :memory: provider for my tests. Getting this error when I attempt to query using the IRepository<TEntity, Guid> service. It occurs whether I use it directly in a test method, or the instance injected into the service.
System.ObjectDisposedException : Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Does anyone know what is causing this error, I can't seem to figure it out. Have I mis-configured something in the test modules?
HolidaySchedule schedule = await _holidayScheduleRepository.GetAsync(x => x.TenantId == tenantId
&& x.Id == id);
In case anyone has this issue, my problem was that I wasn't using the unit of work properly. My test cases needed to be wrapped in a WithUnitOfWork.. block which I overlooked.
await WithUnitOfWorkAsync(async () =>
{
ISomeService service = GetRequiredService<ISomeService>();
int result = await service.DoSomethingAsync();
Assert.Equal(5, result);
});

Apollo client not paring UserInputError

i am throwing an UserInputError from the Apollo server, the playground is correctly displaying the error with extension and exceptions, but the the apollo client is not showing the extensions and exceptions.
Stringify the error and found that ,we can access it using error.graphQlErrors[0] , it's weird that it's not written anywhere in the documentation. This sure gave me a lot of trouble
The existing answer worked for me. Just providing some more details to help future Googlers.
On the apollo-server backend, we are throwing an error:
throw new UserInputError("Form Arguments invalid", {
field: "name",
});
On the apollo-client frontend, we are catching that error:
try {
// Perform GraphQL mutation.
} catch (error) {
// How do we get the "field" extra info?
}
As the previous answer says, there is some graphQlErrors property that contains extra information. So in this example, I can access error.graphQlErrors[0].extensions.field to get the "name" value.

Several GET Methods in ASP .NET WEB API causing 500 when sending array using URI

In my ASP .NET WEB API, I want to use the following methods:
[Route(""), HttpGet]
public IDictionary<int, string> GetAll()
{
//doSth
}
[Route(""), HttpGet]
public IDictionary<int, string> GetSpecificOnes([FromUri]IEnumerable<int> carsIds)
{
//doSth
}
When requesting the second one using angular, I get the following exception:
angular.js:12011 GET http://localhost:12345/_api/cars?&carsIds[0]=1&carsIds[1]=2&carsIds[2]=5 500 (Internal Server Error)
I think the problem is, that I have two GET-Methods without a route. But I don't need one. How do I solve this problem?
You actually don't need to define a route, like you say, as long as the GET methods in the controllers have different signatures and parameterlist.
The problem in your case is that you call the method the wrong way.
Either change the parameter name in the api method to carsIds or change the angular HTTP query string to ?ids[0]=1&ids[1]=2&ids[2]=5

Parsing Swagger JSON data and storing it in .net class

I want to parse Swagger data from the JSON I get from {service}/swagger/docs/v1 into dynamically generated .NET class.
The problem I am facing is that different APIs can have different number of parameters and operations. How do I dynamically parse Swagger JSON data for different services?
My end result should be list of all APIs and it's operations in a variable on which I can perform search easily.
Did you ever find an answer for this? Today I wanted to do the same thing, so I used the AutoRest open source project from MSFT, https://github.com/Azure/autorest. While it looks like it's designed for generating client code (code to consume the API documented by your swagger document), at some point on the way producing this code it had to of done exactly what you asked in your question - parse the Swagger file and understand the operations, inputs and outputs the API supports.
In fact we can get at this information - AutoRest publically exposes this information.
So use nuget to install AutoRest. Then add a reference to AutoRest.core and AutoRest.Model.Swagger. So far I've just simply gone for:
using Microsoft.Rest.Generator;
using Microsoft.Rest.Generator.Utilities;
using System.IO;
...
var settings = new Settings();
settings.Modeler = "Swagger";
var mfs = new MemoryFileSystem();
mfs.WriteFile("AutoRest.json", File.ReadAllText("AutoRest.json"));
mfs.WriteFile("Swagger.json", File.ReadAllText("Swagger.json"));
settings.FileSystem = mfs;
var b = System.IO.File.Exists("AutoRest.json");
settings.Input = "Swagger.json";
Modeler modeler = Microsoft.Rest.Generator.Extensibility.ExtensionsLoader.GetModeler(settings);
Microsoft.Rest.Generator.ClientModel.ServiceClient serviceClient;
try
{
serviceClient = modeler.Build();
}
catch (Exception exception)
{
throw new Exception(String.Format("Something nasty hit the fan: {0}", exception.Message));
}
The swagger document you want to parse is called Swagger.json and is in your bin directory. The AutoRest.json file you can grab from their GitHub (https://github.com/Azure/autorest/tree/master/AutoRest/AutoRest.Core.Tests/Resource). I'm not 100% sure how it's used, but it seems it's needed to inform the tool about what is supports. Both JSON files need to be in your bin.
The serviceClient object is what you want. It will contain information about the methods, model types, method groups
Let me know if this works. You can try it with their resource files. I used their ExtensionLoaderTests for reference when I was playing around(https://github.com/Azure/autorest/blob/master/AutoRest/AutoRest.Core.Tests/ExtensionsLoaderTests.cs).
(Also thank you to the Denis, an author of AutoRest)
If still a question you can use Swagger Parser library:
https://github.com/swagger-api/swagger-parser
as simple as:
// parse a swagger description from the petstore and get the result
SwaggerParseResult result = new OpenAPIParser().readLocation("https://petstore3.swagger.io/api/v3/openapi.json", null, null);

App Engine Instance ID

Is it possible to get info on what instance you're running on? I want to output just a simple identifier for which instance the code is currently running on for logging purposes.
Since there is no language tag, and seeing your profile history, I assume you are using GAE/J?
In that case, the instance ID information is embedded in one of the environment attributes that you could get via ApiProxy.getCurrentEnvironment() method. You could then extract the instance id from the resulting map using key BackendService.INSTANCE_ID_ENV_ATTRIBUTE.
Even though the key is stored in BackendService, this approach will also work for frontend instances. So in summary, the following code would fetch the instance ID for you:
String tInstanceId = ApiProxy.getCurrentEnvironment()
.getAttributes()
.get( BackendService.INSTANCE_ID_ENV_ATTRIBUTE )
.toString();
Please keep in mind that this approach is quite undocumented by Google, and might subject to change without warning in the future. But since your use case is only for logging, I think it would be sufficient for now.
With the advent of Modules, you can get the current instance id in a more elegant way:
ModulesServiceFactory.getModulesService().getCurrentInstanceId()
Even better, you should wrap the call in a try catch so that it will work correctly locally too.
Import this
import com.google.appengine.api.modules.ModulesException;
import com.google.appengine.api.modules.ModulesServiceFactory;
Then your method can run this
String instanceId = "unknown";
try{
instanceId = ModulesServiceFactory.getModulesService().getCurrentInstanceId();
} catch (ModulesException e){
instanceId = e.getMessage();
}
Without the try catch, you will get some nasty errors when running locally.
I have found this super useful for debugging when using endpoints mixed with pub-sub and other bits to try to determine why some things work differently and to determine if it is related to new instances.
Not sure about before, but today in 2021 the system environment variable GAE_INSTANCE appears to contain the instance id:
instanceId = System.getenv("GAE_INSTANCE")

Resources