F#: How to include external test data in mstest unit tests - f#

I want to test my code with some data defined in an external file.
I tried the following:
namespace blub
open System
open Microsoft.VisualStudio.TestTools.UnitTesting
[<TestClass>]
type TestClass () =
[<TestMethod>]
member this.TestMethodPassing () =
let txt = System.IO.File.ReadAllText "data.txt"
Assert.IsTrue(txt.Contains "Hello");
I just created the project with dotnet new mstest -lang F# and put the data.txt file next to the Test.fs file.
However, when I run the tests with dotnet test I get the following error:
Failed TestMethodPassing
Error Message:
Test method blub.TestClass.TestMethodPassing threw exception:
System.IO.FileNotFoundException: Could not find file '/home/peter/Desktop/blub/bin/Debug/netcoreapp2.1/data.txt'.
Stack Trace:
at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.File.InternalReadAllText(String path, Encoding encoding)
at System.IO.File.ReadAllText(String path)
at blub.TestClass.TestMethodPassing() in /home/peter/Desktop/blub/Tests.fs:line 11
I can of course fix this by changing the path to "../../../data.txt", but this does not seem like a stable solution -- I did not find any documentation that states how test execution affects the current directory.
Can I somehow declare my test file as a resource to be copied to the correct folder?

You will need to add the data.txt file to the fsproj and set it to copy to the output folder:
<ItemGroup>
<Content Include="data.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
If it still isn't found, you may you need to use the [<DeploymentItem("data.txt")>] against the TestClass.
This will copy the files from the output folder to the folder where the tests are executed.

Related

Could not find file Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream

I'm running an Azure Function locally in Visual Studio but receive the error "Could not find file 'C:\Users\kbiondi\AppData\Local\AzureFunctionsTools\Releases\4.13.0\cli_x64\Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream'. (details below).
The code that triggers this error seems to be:
let! parameters = JsonTypeProvider.AsyncLoad(req.Body.ToString())
Using let parameters = JsonTypeProvider.Load(req.Body) the function runs without problem.
I have reloaded various nuget packages and the sdk, but this problem persists.
Azure Functions Core Tools Core Tools Version: 4.0.4483 Commit
hash: N/A (64-bit) Function Runtime Version: 4.1.3.17473
[2022-05-19T18:24:10.578Z] Csproj not found in
C:\Users\kbiondi\OneDrive -
CalPERS\Repos\AzFunction_BpipeRefData\bin\Debug\net6.0 directory tree.
Skipping user secrets file configuration.
Functions:
BpipeReferenceDataRequest: [GET,POST] http://localhost:7071/api/BpipeReferenceDataRequest
For detailed output, run func with --verbose flag.
[2022-05-19T18:24:16.773Z] Host lock lease acquired by instance ID
'0000000000000000000000001F77FD18'. [2022-05-19T18:24:43.597Z]
Executing 'BpipeReferenceDataRequest' (Reason='This function was
programmatically called via the host APIs.',
Id=13a1beaf-3141-4112-a086) The Azure Function Received a
Request... Request failed with the following error:
Message: Could not find file
'C:\Users\kbiondi\AppData\Local\AzureFunctionsTools\Releases\4.13.0\cli_x64\Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream'.
Source: System.Private.CoreLib
TargetSite: Microsoft.Win32.SafeHandles.SafeFileHandle
CreateFile(System.String, System.IO.FileMode, System.IO.FileAccess,
System.IO.FileShare, System.IO.FileOptions)
StackTrace: at
Microsoft.Win32.SafeHandles.SafeFileHandle.CreateFile(String fullPath,
FileMode mode, FileAccess access, FileShare share, FileOptions
options) at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String
fullPath, FileMode mode, FileAccess access, FileShare share,
FileOptions options, Int64 preallocationSize) at
System.IO.Strategies.OSFileStreamStrategy..ctor(String path, FileMode
mode, FileAccess access, FileShare share, FileOptions options, Int64
preallocationSize) at
FSharp.Data.Runtime.IO.asyncRead#219-9.Invoke(Unit unitVar) at
Microsoft.FSharp.Control.AsyncPrimitives.CallThenInvoke[T,TResult](AsyncActivation1 ctxt, TResult result1, FSharpFunc2 part2) in
D:\a_work\1\s\src\fsharp\FSharp.Core\async.fs:line 447 at
BpipeProcess.BpipeReferenceDataRequest.Pipe #1 input at line
16#21-11.Invoke(AsyncActivation1 ctxt) at BpipeProcess.BpipeReferenceDataRequest.Pipe #1 input at line 16#20-14.Invoke(AsyncActivation1 ctxt) at
Microsoft.FSharp.Control.Trampoline.Execute(FSharpFunc`2 firstAction)
in D:\a_work\1\s\src\fsharp\FSharp.Core\async.fs:line
104[2022-05-19T18:24:43.679Z] Executed 'BpipeReferenceDataRequest'
(Succeeded, Id=13a1beaf-3141-4112-a086, Duration=101ms)
Based on the MICROSOFT DOCUMENTATION:-
F# script (.fsx) is only supported by version 1.x of the Azure
Functions runtime. If you want to use F# with version 2.x and later
versions of the runtime, you must use a precompiled F# class library
project (.fs). You create, manage, and publish an F# class library
project using Visual Studio .
You can use in that line if wants http request e.g:- let Run(req: HttpRequestMessage, log: ILogger) =
And make sure that your folder structure looks like below format:
FunctionsProject
| - MyFirstFunction
| | - run.fsx
| | - function.json
| | - function.proj
| - MySecondFunction
| | - run.fsx
| | - function.json
| | - function.proj
| - host.json
| - extensions.csproj
| - bin
For more information please refer the aforementioned and below links:
SIMILAR ISSUE|SO THREAD
MICROSOFT DOCUMENT|Microsoft.AspNetCore.WebUtilities Namespace
BLOG|Microsoft.AspNetCore.WebUtilities FileBufferingReadStream Examples

How To Require Lua Socket?

I'm very new to lua development with file manipulation, and now trying to import the lua socket package into my project according to this post, but I can't run even the code below.
I guess the error message indicates I need to import not only the socket.lua but also .\socket\core (probably .dll, since it doesn't have core.lua), while a reply at the post suggested importing only the file.
I'm stuck in just the beginning... What do I have to do for the next step?
local function main()
local socket = require("socket")
end
main()
Exception in thread "main" com.naef.jnlua.LuaRuntimeException: ...n32.win32.x86_64\workspace\TestForCiv\src\socket.lua:13: module 'socket.core' not found:
no field package.preload['socket.core']
no file '.\socket\core.lua'
no file 'C:\Program Files\Java\jre1.8.0_151\bin\lua\socket\core.lua'
no file 'C:\Program Files\Java\jre1.8.0_151\bin\lua\socket\core\init.lua'
...(a bunch of no file errors continues)
Edit: I added the folder structure. Even I add the .dll file it returns the same error.
I don't know the details of you configuration, but try this
require ("src.socket")
you should require a module from the root path of the lib

drools DRL classpath resource

I have a grails app with an XMLSolverFactory, loading it's XML configuration file from ./myapp/grails-app/conf/ with the code below. It cannot find the DRL file from the same path though. How can I get an XML configured Solver to find a classpath .DRL resource if it's running in a container?
def InputStream stream = this.getClass().classLoader.getResourceAsStream("nurseRosteringSolverConfig.xml")
solverFactory.configure(stream);
The configuration XML snippet
<scoreDrl>nurseRosteringScoreRules.drl</scoreDrl>
throws the error
scoreDrl (nurseRosteringScoreRules.drl) does not exist as a classpath resource
The getClass() code might prefix the package of your class.
Suppose your class file is in package org.foo.bar and your nurseRosteringScoreRules.drl is also in that package, then you 'd write:
<scoreDrl>/org/foo/bar/nurseRosteringScoreRules.drl</scoreDrl>

EF.Utility.CS.ttinclude and MSBuild

I am having troubles getting my MSBuild script transform a .tt file that references EF.Utility.CS.ttinclude.
If i run the generation from within VS2010 it works fine, but when I run my custom build script via the command line I get.
TextTransform "C:\SourceControl\SVN\PathToFile\myttFile.tt"
C:\SourceControl\SVN\PathToFile\myttFile.tt(9,4): error : There was an error loading the include file 'EF.Utility.CS.ttinclude'. The transformation will not be run. The following Exception was thrown: [C:\SourceControl\SVN\PathToBuildScript\build.xml]
System.IO.FileNotFoundException: Could not find file 'C:\SourceControl\SVN\PathToFile\EF.Utility.CS.ttinclude'.
File name: 'C:\SourceControl\SVN\PathToFile\EF.Utility.CS.ttinclude'
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path)
at Microsoft.VisualStudio.TextTemplating.CommandLine.CommandLineHost.ReadFileContent(String fileName)
at Microsoft.VisualStudio.TextTemplating.CommandLine.CommandLineHost.LoadIncludeText(String requestFileName, String& content, String& location)
at Microsoft.VisualStudio.TextTemplating.Engine.ProcessIncludeDirective(Directive directive, ITextTemplatingEngineHost host)
C:\SourceControl\SVN\PathToBuildScript\build.xml(30,5): error MSB3073: The command "TextTransform "C:\SourceControl\SVN\PathToFile\myttFile.tt"" exited with code 1.
If I reference the absolute path for the EF.Utility.CS.ttinclude, I get:
TextTransform "C:\SourceControl\SVN\PathToFile\myttFile.tt"
EXEC : error : An expression block evaluated as Null [C:\SourceControl\SVN\PathToBuildFile\build.xml]
at Microsoft.VisualStudio.TextTemplating.ToStringHelper.ToStringWithCulture(Object objectToConvert)
at Microsoft.VisualStudio.TextTemplatinga265b58e2b114039856ebd504775f376.GeneratedTextTransformation.TransformText() in c:\SourceControl\SVN\PathToFile\myttFile.tt:line 77
at Microsoft.VisualStudio.TextTemplating.TransformationRunner.RunTransformation(TemplateProcessingSession session, String source, ITextTemplatingEngineHost host, String& result)
C:\SourceControl\SVN\PathToBuildFile\build.xml(30,5): error MSB3073: The command "TextTransform "C:\SourceControl\SVN\PathToFile\myttFile.tt"" exited with code 1.
Any help would be great :)
In short: Add the -I flag in TextTransform.exe to solve this problem like so:
Step 1:
Create an environment variable mapping to your TextTransform's EF6 Include like so:
which will create a variable VS140COMNTXTTRANSFORM that Windows understands
Step 2:
Include -I flag in the TextTransform.exe command like so:
TextTransform.exe -I "%VS140COMNTXTTRANSFORM%" -out filename.tt
Appears that the template you were running myttFile.tt failed out output anything as a result of the template being executed TransformText();
Can't really tell much without seeing what the logic is inside of myttFile.tt.
Visual Studio 11 if you
set <# template debug = true#>
and add
System.Diagnostics.Debugger.Launch();
to the code section of your template, VS 11 will launch the debugger and you can debug your t4.
sorry, just dawned on me. Chances are your template has a dependency on visual studio as its host. somewhere in your templates you have hostspecific = true.
<## template hostspecific="true" language="C#" #>

Ant scp task failure

I have one requirement: copy local files to remote system.
I have done the following:
downloaded jsch-0.1.44.jar and copied to lib folder of Ant
set the path and every thing
My buildfile is:
<project name="ImportedBuild" default="all">
<target name="copyFileToRemote">
<echo>2222222222 copyFileToRemote Examples:::::::::::::</echo>
<scp file="sample.txt" todir="${username}:${password}#${hostname}:/shared"/>
</target>
</project>
When I run Ant, I get this error:
BUILD FAILED com.jcraft.jsch.JSchException: reject HostKey: 10.184.74.168
at com.jcraft.jsch.Session.checkHost(Session.java:712)
at com.jcraft.jsch.Session.connect(Session.java:313)
at com.jcraft.jsch.Session.connect(Session.java:154)
at org.apache.tools.ant.taskdefs.optional.ssh.SSHBase.openSession(SSHBase.java:212)
at org.apache.tools.ant.taskdefs.optional.ssh.Scp.upload(Scp.java:291)
at org.apache.tools.ant.taskdefs.optional.ssh.Scp.execute(Scp.java:203)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
... etc ...
Any ideas how to resolve this?
According to the Ant scp task docs, trust attribute:
This trusts all unknown hosts if set
to yes/true. Note If you set this to
false (the default), the host you
connect to must be listed in your
knownhosts file, this also implies
that the file exists.
The trust attribute is not used in your task call, so it appears that the host (10.184.74.168) is not in your knownhosts file. Suggest you add trust="true", or add the host to the knownhosts file.
Be sure your ~/.ssh/known_hosts file is using un-hashed hostnames; if the lines start |1|base64data..., JSch appears unable to parse them. Create lines of the format hostname[,hostname|ip]* ssh-keytype base64data....
See man 8 sshd on the precise format of known_hosts, and tips on where to find the host's public key.

Resources