How can I include sample data files in VS unit tests? - visual-studio-2010

I've got unit tests I want to run against a sample XML file. How should I go about exposing these files to the unit tests? I've tried playing with the content build action, but I don't have access to an application context so GetContentStream is out.
I'm aware I can use a DataContext to a SQL Database, but I feel this is the wrong approach.

If you are looking to deploy the XML file with your tests, you have a few options:
Embedded Content
You can embed the Xml file as content within the assembly.
Add the file to your test project. In the context of this example, the file is located at the root of the project.
Change the properties of the file to be an Embedded Resource.
During the test you can get access to the file as a stream by using the get manifest resource.
Example:
[TestMethod]
public void GetTheFileFromTheAssembly()
{
Stream fileStream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("MyNamespace.File.xml");
var xmlDoc = new XmlDocument();
xmlDoc.Load(fileStream);
Assert.IsNotNull( xmlDoc.InnerXml );
}
DeploymentItemAttribute
You can annotate the test method or class with a [DeploymentItemAttribute]. The file path is relative to the solution.
[DeploymentItem("file.xml")] // file is at the root of the solution
[TestMethod]
public void GetTheFileDeployedWithTheTest()
{
var xmlDoc = new XmlDocument();
xmlDoc.Load("file.xml");
Assert.IsNotNull(xmlDoc.InnerXml);
}
Test Settings
You can deploy individual files or entire directories using the Deployment configuration inside the Test Settings file. (Tests -> Edit Settings -> Filename.testsettings)

Related

Spring boot must to create a file before the application.properties are load

I'm working currently on a Spring boot project, and we have an application.properties file that defines a path where we have 2 jks files. (the original file has more key/value pairs, but I'm focusing in the main problem with these two pairs)
example
file1.example=folder/file1.jks
file12.example=folder/file2.jks
But now, I need to read an environment variable that contains an encoded value that I need to take, decode and use to create these files. The main problem is that I need to create these two files before the properties are "loaded" because these files do not exist, if I first don't build them, any idea?
Normally Spring boot launches from the following main method. You can define a static method before the launcher is called so that in that method you use whatever environment variable you want and make I/O operations to prepare the files. Then if this is done successfully you can let Spring Boot start the server and application normally.
#SpringBootApplication
public class ConfigurationApplication {
public static void main(String[] args) {
createPropertiesFiles(); <---------------
SpringApplication.run(ConfigurationApplication.class, args);
}
private static void createPropertiesFiles(){
// I/O operations to create those files ...
}
}

Quarkus Qute template location from another maven module

Having a maven module that declares a Qute template and REST endpoint to render it, I wanted to include this module on another maven project. The problem is, at it seems, the destination module does not compile since it does not have / find the template in it's resources/templates location (the template is included in the jar of the included module).
Is there any way to instruct Qute (at build time) to read templates from other locations or disable this build check (since the template is in the classpath at the correct location?
The only way I can make it work roght now is to copy my template to the destination project at resources/templates but it doesn't seem the right solution.
Thanks in advance
Yes, by default only the templates located in src/main/resources/templates are validated and can be injected.
You can parse any template content manually via Engine.parse() or even add a custom template locator via io.quarkus.qute.EngineBuilder.addLocator(), e.g. something like:
import io.quarkus.qute.EngineBuilder;
class MyEngineConfig {
void configureEngine(#Observes EngineBuilder builder) {
builder.addLocator(path -> Optional.of(new TemplateLocation() {
#Override
public Reader read() {
return new BufferedReader(new InputStreamReader(FlowChartResource.class.getResourceAsStream(path)));
}
#Override
public Optional<Variant> getVariant() {
return Optional.empty();
}
}));
}
}
The disadvantage is that Quarkus can't validate/inject such templates.
See also related issues https://github.com/quarkusio/quarkus/issues/12084 and https://github.com/quarkusio/quarkus/issues/10376.
Ok, I found another solution, using "low-level" engine instance and parsing the template "manualy":
engine.parse(new BufferedReader(new InputStreamReader(FlowChartResource.class.getResourceAsStream([PATH to My Template]))).lines().collect(Collectors.joining("\n")))

swagger codegen add #JacksonXmlElementWrapper(useWrapping = false) annotation to a single field

I'm currently using swagger codegen using yml to generate my models However I have one field, that is a List<Object> that needs to have the #JacksonXmlElementWrapper(useWrapping = false). I can see the #JacksonXmlElementWrapper in POJO.mustache but not in model.mustache. Does anyone know what to add in the yaml file or anywhere else so that field gets generated with that annotation? Thanks. I'm using spring-java language with gradle. I need this to be generated during build. so minimal changes are preferred.
According to the readme on their git, Swagger Codegen mention ways to do this:
https://github.com/swagger-api/swagger-codegen/blob/master/README.md
since you're using gradle:
We can use a custom template for the code generation as follows:
// build.gradle
swaggerSources {
inputFile = file('{name of your file}.yaml')
xyz {
language = 'spring'
// template directory path
templateDir = file('templates/{name of your custom directory}')
}
}
inside templates/{name of your custom directory}, you can store your custom mustache files, as in your case, all you have to do is download the required spring templates from git (e.g. this link is for pojo.mustache)
and add in the required changes to the template, along with the project and libraries folder. Run gradle build and it should generate.
There is a much simpler workaround however, where you can just use your own pojo class and add this in your existing config.json and remove the earlier entry for that model in your yaml file (of course):
"importMappings" : {
"{replace with className}": "{replace with packageName}.{replace with className}"
}
Hope this helps.

nullreference exception

Using Linq to sql and server explorer, I mapped to a loginvalidation stored proc. So I write the following code:
ClientReportingDataContext db = new ClientReportingDataContext();
var data = db.ADMIN_LoginValidation(login, password);
It throws up an exception on the following line:
public ClientReportingDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["FeedsConnectionString"].ConnectionString, mappingSource)
Exception thrown:
Object reference not set to an instance of an object.
I'm calling this function from a unit test class. I cann feedsconnectionstring in web.config.
I put the web.config in the unit tests folder, and also under debug and debug/bin. Not sure what I'm missing.
Thanks in advance for any advise.
For a unit test,
ConnectionStrings["FeedsConnectionString"].ConnectionString
won't be reading from your web.config file; it will be reading from the application configuration file for the test runner. Therefore, unless you've put FeedsConnectionString in the application configuration file for your test runner,
ConnectionStrings["FeedsConnectionString"]
is null and so
ConnectionStrings["FeedsConnectionString"].ConnectionString
is going to throw a NullReferenceException.
This is why testing and application configuration files don't get along well.
You should consider the following:
public ClientReportingDataContext(string connectionString) :
base(connectionString, mappingSource)
Then inject your connection string in your test.

Setting freemarker template from classpath

I have a web application that I need to manually obtain a Freemarker template - the template is obtained via a class in a library project, but the actual tpl file is contained in the web application classpath. So, there are 2 projects, one 'taac-backend-api' and another 'taac-web'; taac-backend-api has the code to grab the template, and process it, but taac-web is where the template is stores (specifically in: WEB-INF/classes/email/vendor.tpl) - I have tried everything from using springs classpath resource to using Freemarkers setClassForTemplateLoading method. I assume this would work:
freemarkerConfiguration = new Configuration();
freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "");
Template freemarkerTemplate = freemarkerConfiguration.getTemplate("/email/vendor.tpl");
yet, I always get a FileNotFoundException. Can someone explain the best way to obtain a template from the classpath?
Thanks.
this is what ended up working for me:
freemarkerConfiguration = new Configuration(Configuration.VERSION_2_3_28);
freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/");
Template freemarkerTemplate = freemarkerConfiguration.getTemplate("email/vendor.tpl");
In 2017, the following is deprecated:
Configuration conf = new Configuration();
We should pass freemarker.template.Version to the constructor:
Configuration conf = new Configuration(new Version(2, 3, 23));
conf.setClassForTemplateLoading(Application.class, "/views");
where the version numbers refer to the current version of FreeMarker.
The views directory is located in src/main/resources.
freemarkerConfiguration = new Configuration();
freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "");
Template freemarkerTemplate = freemarkerConfiguration.getTemplate("template.tpl");
Use this method to load the classes from the package where your class is located, so if your class is
org.foo.SomeClass the templates will be looked for in /org/foo in the classpath. This keeps your templates stored with the class that uses/loads them.
If you are using Struts 2 and the Conventions plugin, wuntee's solution doesn't seem to work: setClassForTemplateLoading in turn creates an instance of ClassTemplateLoader which doesn't find files in jars no matter what path prefix is specified.
Instead, create an instance of StrutsClassTemplateLoader. (I do this in a custom sub-class of FreemarkerManager in its getTemplateLoader method.) It takes no parameters, so presumably it just knows how Struts and Conventions do things.
Use the following config and place it in application properties.
spring.freemarker.template-loader-path=

Resources