ASP.Net Core React spa integration test - reactjs

Asp.Net Core integration testing seems pretty simple but for the life of me I can't test the starter app with my react dev server. It runs fine from a browser so I assume node, npm and react are set up correctly but not under xUnit. It fails with the following exception:
System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> System.InvalidOperationException: Failed to start 'npm'. To resolve this:.
[1] Ensure that 'npm' is installed and can be found in one of the PATH directories.
Current PATH enviroment variable is: {PATH}
Make sure the executable is in one of those directories, or update your PATH.
[2] See the InnerException for further details of the cause. ---> System.ComponentModel.Win32Exception: The directory name is invalid
...
I assume this is because it can't find the content root of my spa so I have tried adding to my web host builder with no luck:
.UseSolutionRelativeContentRoot( "Solution Relative Path to My App" ) );
This is my test class:
public class SampleDataControllerTest
{
private readonly TestServer server;
private readonly HttpClient client;
public SampleDataControllerTest()
{
server = new TestServer( WebHost.CreateDefaultBuilder()
.UseStartup<Startup>()
.UseSolutionRelativeContentRoot( "Solution Relative Path to My App" ) );
.UseEnvironment( "Development" );
client = server.CreateClient();
}
[Fact]
public async Task RootTest()
{
HttpResponseMessage page = await client.GetAsync( "/" );
Assert.NotNull( page );
Assert.Equal( HttpStatusCode.OK, page.StatusCode );
}
What am I missing?

The trick for me was setting the development environment variable to point to the directory where the packages.json file resides.
Below is an excerpt of the constructor of my xUnit integration test class.
Note that it first determines the solution directory (using GetExecutingAssembly().Location), and then points to the web source project folder. (In our environment, Client.React is a directory under the solution directory that contains the packages.json file).
Then, the directory is set using Directory.SetCurrentDirectory, followed by the test server being set up wit hthe UseWebRoot, again pointing to the directory where the packages.json file resides.
Startup is the ASP.NET web startup class.
/// <summary>
/// Constructor
/// </summary>
public IntegrationTest() : base()
{
var testAssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
// Remove the "\\bin\\Debug\\netcoreapp2.1"
var solutionPath = Directory.GetParent(testAssemblyPath.Substring(0, testAssemblyPath.LastIndexOf(#"\bin\", StringComparison.Ordinal))).FullName;
var clientReactPath = Path.Join(solutionPath, "Client.React");
// Important to ensure that npm loads and is pointing to correct directory
Directory.SetCurrentDirectory(clientReactPath);
var server = new TestServer(new WebHostBuilder()
.UseEnvironment("Development")
.UseWebRoot(clientReactPath)
.UseStartup<Startup>());
_client = server.CreateClient();
}

Related

My service is not recognizing the file names contained in directory with Java 8

I am creating a service and I am using java 8, I want to retrieve the file names as a list, those are in a folder into resources/ and when I am running locally is working but when I deployed my application into DEV/QA environment is getting empty, is not recognizing those files, and I have some considerations:
In the full path, in one folder is hidden folder (.cache), that
could affect it?, this is the path:
file:/newarch/apps/project-1/servers/project-service-1/workarea/org.eclipse.osgi/55/data/cache/com.ibm.ws.app.manager_723/.cache/project-service-ser.jar!/services
I gave rights on the folder as reader and writer.
This is the structure of the folder that I wanna retrieve the names:
resources/
services/
service-host1.js
service-host2.js
service-host3.js
service-host4.js
This is my code to read:
public List<String> getFilesFromDirectory(String dirName) throws IOException {
dirName = dirName + "/";
try (Stream<Path> pathStream = Files.list(Paths.get(dirName))) {
return pathStream.filter(Files::isRegularFile)
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toList());
}
}
this is the way how I am getting the full path:
Thread.currentThread().getContextClassLoader().getResource("service").getPath()
Could you give any advice what could be the problem?

Upgrade dependency camel-spring-batch / spring-batch-component

When upgrading from:
https://camel.apache.org/components/2.x/spring-batch-component.html
to:
https://camel.apache.org/components/3.18.x/spring-batch-component.html
query parameter "synchronous" is dropped.
Can I assume "synchronous=true",
for camel-spring-batch 3.18.2 ?
Looking at the apache-camel project on github it was removed due to lack of components that supported a flag of that ilk.
The default job launcher in spring batch launches jobs synchronously. If you wanted to run a job asynchonously you would have to configure your own job launcher and use use an asynctaskexecutor like below
#Bean(name = "asyncJobLauncher")
public JobLauncher asyncJobLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}

FailedToStartRouteException exception while using camel-spring-boot, amqp and kafka starters with SpringBoot, unable to find connectionFactory bean

I am creating an application using Apache Camel to transfer messages from AMQP to Kafka. Code can also be seen here - https://github.com/prashantbhardwaj/qpid-to-kafka-using-camel
I thought of creating it as standalone SpringBoot app using spring, amqp and kafka starters. Created a route like
#Component
public class QpidToKafkaRoute extends RouteBuilder {
public void configure() throws Exception {
from("amqp:queue:destinationName")
.to("kafka:topic");
}
}
And SpringBoot application configuration is
#SpringBootApplication
public class CamelSpringJmsKafkaApplication {
public static void main(String[] args) {
SpringApplication.run(CamelSpringJmsKafkaApplication.class, args);
}
#Bean
public JmsConnectionFactory jmsConnectionFactory(#Value("${qpidUser}") String qpidUser, #Value("${qpidPassword}") String qpidPassword, #Value("${qpidBrokerUrl}") String qpidBrokerUrl) {
JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory(qpidPassword, qpidPassword, qpidBrokerUrl);
return jmsConnectionFactory;
}
#Bean
#Primary
public CachingConnectionFactory jmsCachingConnectionFactory(JmsConnectionFactory jmsConnectionFactory) {
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(jmsConnectionFactory);
return cachingConnectionFactory;
}
jmsConnectionFactory bean which is created using Spring Bean annotation should be picked by amqp starter and should be injected into the route. But it is not happening. When I started this application, I got following exception -
org.apache.camel.FailedToStartRouteException: Failed to start route route1 because of Route(route1)[From[amqp:queue:destinationName] -> [To[kafka:.
Caused by: java.lang.IllegalArgumentException: connectionFactory must be specified
If I am not wrong connectionFactory should be created automatically if I pass right properties in application.properties file.
My application.properties file looks like :
camel.springboot.main-run-controller = true
camel.component.amqp.enabled = true
camel.component.amqp.connection-factory = jmsCachingConnectionFactory
camel.component.amqp.async-consumer = true
camel.component.amqp.concurrent-consumers = 1
camel.component.amqp.map-jms-message = true
camel.component.amqp.test-connection-on-startup = true
camel.component.kafka.brokers = localhost:9092
qpidBrokerUrl = amqp://localhost:5672?jms.username=guest&jms.password=guest&jms.clientID=clientid2&amqp.vhost=default
qpidUser = guest
qpidPassword = guest
Could you please help suggest why during autoconfiguring connectionFactory object is not being used? When I debug this code, I can clearly see that connectionFactory bean is getting created.
I can even see one more log line -
CamelContext has only been running for less than a second. If you intend to run Camel for a longer time then you can set the property camel.springboot.main-run-controller=true in application.properties or add spring-boot-starter-web JAR to the classpath.
however if you see my application.properties file, required property is present at the very first line.
One more log line, I can see at the beginning of application startup -
[main] trationDelegate$BeanPostProcessorChecker : Bean 'org.apache.camel.spring.boot.CamelAutoConfiguration' of type [org.apache.camel.spring.boot.CamelAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Is this log line suggesting anything?
Note - One interesting fact that exactly same code was running fine last night, just restarted my desktop and there is not even a single word changed and now it is throwing exception.
This just refers to an interface
camel.component.amqp.connection-factory = javax.jms.ConnectionFactory
Instead it should refer to an existing factory instance, such as
camel.component.amqp.connection-factory = #myFactory
Which you can setup via spring boot #Bean annotation style.

unable to access file in resources/static folder spring-boot

I have a file in a location:
/resources/static/fcm-admin
It's absolute path: /home/jitu/project-name/src/main/resources/static/fcm-admin
I have tried to access this file in the following ways
val file = ResourceUtils.getFile("classpath:fcm-admin")
It gives me an error
java.io.FileNotFoundException: class path resource [fcm-admin] cannot be resolved to an absolute file path because it does not exist
I have tried to access the file in various ways but it is not working. I just want to the access file fcm-admin without giving the full absolute path. Anything will be helpful
EDIT:
So I'm able to access the file on local with the below code -
val file = ResourceUtils.getFile("classpath:static/fcm-admin")
But I'm not able to access it on the production server. And I'm getting below exception
class path resource [static/fcm-admin] cannot be resolved to an absolute file path because it does not reside in the file system: jar:file:/var/app/current/application.jar!/BOOT-INF/classes!/static/apple-app-site-association
You forgot to add static in the path
val file = ResourceUtils.getFile("classpath:static/fcm-admin")
EDIT because of comment
Load your file from Classpath:
val file = this.javaClass.classLoader.getResource("/static/fcm-admin").file;
When you load a resource using the class loader it will be start in the root of your classpath.
Local server can work with ClassPathResource but will fail on production
To solve error on production, change your code to
import org.springframework.core.io.ResourceLoader;
import java.io.InputStream;
import org.springframework.core.io.InputStreamSource;
import org.springframework.core.io.ByteArrayResource;
import org.apache.commons.io.IOUtils;
#Autowired
private ResourceLoader resourceLoader;
InputStream logoFileStrem = resourceLoader.getResource("classpath:static/images/image.png").getInputStream();
InputStreamSource byteArrayResource = new ByteArrayResource(org.apache.commons.io.IOUtils.toByteArray(logoFileStrem));
I spent so many time, lot of code work on dev but not on prod.
I used SpringBoot with war in production.
To load a file in resources/static the only solution who work in dev and in prod :
val inputStream = Thread.currentThread().contextClassLoader.getResourceAsStream("static/pathToTourFile/nameofFile.extension")
val texte :String = inputStream.bufferedReader().use(BufferedReader::readText)

bug in aspnet_compiler?

I have a solution with several web projects.
I have built each project into its own folder (there's about 10 projects):
/build/projA
/build/projB
/build/projC
If I call
aspnet_compiler -v / -p \"build/#{proj}\" merged/#{proj}
on each one in turn, everything is fine.
If I make all 10 calls to aspnet_compiler in parallel, I get assembly loading errors, saying the referenced assemblies are in use.
Is this a bug? Why would it be in use? It shouldn't be.
The assemblies that cant be loaded are in multiple projects, but each one has its own copy in its bin folder.
Update: it seems to occur (for some) of the assemblies that are references of references. Those loaded with complete binding information seem to work.
Here's a dump from one of the failed loadings from fuslogvw
The operation failed.
Bind result: hr = 0x80070020. The process cannot access the file because it is being used by another process.
Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe
--- A detailed error log follows.
=== Pre-bind state information ===
LOG: User = andrew.bullock
LOG: DisplayName = Yahoo.Yui.Compressor
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Yahoo.Yui.Compressor | Domain ID: 2
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///E:/build/ProjA/
LOG: Initial PrivatePath = E:\build\ProjA\bin
LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\src_projects_proja\061ad2e7
LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\src_projects_proja\061ad2e7
LOG: AppName = 627cc9a9
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: E:\build\ProjA\web.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/src_projects_proja/061ad2e7/627cc9a9/Yahoo.Yui.Compressor.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/src_projects_proja/061ad2e7/627cc9a9/Yahoo.Yui.Compressor/Yahoo.Yui.Compressor.DLL.
LOG: Attempting download of new URL file:///E:/build/ProjA/bin/Yahoo.Yui.Compressor.DLL.
LOG: Assembly download was successful. Attempting setup of file: E:\build\ProjA\bin\Yahoo.Yui.Compressor.dll
LOG: Entering download cache setup phase.
ERR: Error extracting manifest import from file (hr = 0x80070020).
ERR: Setup failed with hr = 0x80070020.
ERR: Failed to complete setup of assembly (hr = 0x80070020). Probing terminated.
If you call the ClientBuildManager directly, outside of aspnet_compiler there doesn't seem to be a problem, no idea why.
var parameter = new ClientBuildManagerParameter
{
PrecompilationFlags = PrecompilationFlags.ForceDebug
};
var client = new ClientBuildManager("/", src, dest, parameter);
client.PrecompileApplication();

Resources