NuGet package restore in Roslyn analyzer test - roslyn-code-analysis

In my unit tests for my Roslyn analyzer, I need to use Microsoft.AspNetCore.Mvc in the test code string. I believe that means I need the long form of testing, so I did the following.
var expected = VerifyCS.Diagnostic(MyAnalyzer.DiagnosticId)
.WithLocation(0)
.WithArguments("Method");
var assemblies = ReferenceAssemblies
.Default
.AddPackages(ImmutableArray.Create(new PackageIdentity("Microsoft.AspNetCore.Mvc.Core", "6.0.0.0")));
await new VerifyCS.Test {
ReferenceAssemblies = assemblies,
TestState = {
Sources = {
test
},
ExpectedDiagnostics = {
expected
}
}
}.RunAsync();
When running the test, it tells me:
Unable to find package 'Microsoft.AspNetCore.Mvc.Core'. Existing packages must be restored before performing an install or update.
I'm not sure how to resolve that in the unit test.

Related

Saving result in a file from vscode-extension unit-tests in Azure DevOps

I have a problem, again...
I try to make a test report from my continuous integration tests in Azure DevOps. I have written unit tests as described in:
https://code.visualstudio.com/api/working-with-extensions/testing-extension
I have written yml mostly as described here:
https://code.visualstudio.com/api/working-with-extensions/continuous-integration
Now I want to "publish" my test results...
I think to publish them, I have to create an XML(or TRX) in one of the following formats: JUnit, NUnit 2, NUnit 3, Visual Studio Test (TRX) and xUnit 2.
It seems I am limited how to create a reporter/testrunner or whatever... I don't get it.
The provided API of vscode looks like:
testRunner.configure({
ui: "tdd",
useColors: true
});
module.exports = testRunner;
The expected type for the API is:
interface MochaSetupOptions {
//milliseconds to wait before considering a test slow
slow?: number;
// timeout in milliseconds
timeout?: number;
// ui name "bdd", "tdd", "exports" etc
ui?: string;
//array of accepted globals
globals?: any[];
// reporter instance (function or string), defaults to `mocha.reporters.Dot`
reporter?: any;
// bail on the first test failure
bail?: boolean;
// ignore global leaks
ignoreLeaks?: boolean;
// grep string or regexp to filter tests with
grep?: any;
// colored output from test results
useColors?: boolean;
// causes test marked with only to fail the suite
forbidOnly?: boolean;
}
I think my best try was using that module https://www.npmjs.com/package/mocha-junit-reporter:
testRunner.configure({
reporter: 'mocha-junit-reporter',
reporterOptions: {
mochaFile: './path_to_your/file.xml'
}
});
I know it fits not the API as described, but when you have a look at the source code from the vscode-module:
function configure(opts) {
mocha = new Mocha(opts);
}
exports.configure = configure;
So it fits the documentation of the "mocha-junit-reporter" module
let a: any = {
ui: "tdd",
reporter: "xunit",
reporterOptions: {
output: normalize(join(getExtensionRootPath(), "..", "TestResults", "unit-tests", os + ".xml")),
}
};
testRunner.configure(a);
this did it for me except for Linux I will edit this answer if get managed it for Linux too.

dynamically put enpoint url through setup scripts

I have two Environment and a lot of test cases, but not all test cases are needed to be run in all environment. Is there a way to run only an specific test cases from a test suite based on the selected Environment. in Setup script .I am using soap ui version 5.4.0 For Example If I select Environment1, it will run the following test cases TC0001 TC0002 If I select Environment2, it will run only the following test cases TC0003 TC0004
Here as I am using "testcases.each" its replacing all endpoint url to one env but i want to exceute based on the testcasename.I am new to the groovy scripting .So can anyone help on this
I am currently using below code but its replacing all endpoint urls in all test cases::
def result = com.eviware.soapui.support.UISupport.prompt("Please select the enviornment", "Environment", ['UAT_API','IT2','UAT1'])
def testcases = testSuite.getTestCaseList()
if(result == 'UAT1'){
testcases.each { testcase ->
def teststeps = testcase.getTestStepList()
teststeps.each { teststep ->
teststep.setPropertyValue('endpoint','')
}
}
}else if(result == 'UAT_API'){
testcases.each { testcase ->
def teststeps = testcase.getTestStepList()
teststeps.each { teststep ->
teststep.setPropertyValue('endpoint','https://a-api.com')
}
}
}else if(result == 'IT2'){
testcases.each { testcase ->
def teststeps = testcase.getTestStepList()
teststeps.each { teststep ->
teststep.setPropertyValue('endpoint','https://it-webservices.com:1')
}
}
}
Can someone give guidance how to proceed from here to?

Compile ReactAndroid, fbjni error

Downloaded from GitHub, to make moudle 'ReactAndroid', then:
Error:(687) Android NDK: Module reactnativejnifb depends on undefined modules: fbjni
Error:(700) *** Android NDK: Aborting (set APP_ALLOW_MISSING_DEPS=true to allow missing dependencies)
Error:Execution failed for task ':ReactAndroid:buildReactNdkLib'.
Process 'command '/Users/sumomokawaakira/Downloads/adt-bundle-mac-x86_64/sdk/ndk-bundle/ndk-build'' finished with non-zero exit value 2
I had this problem too. I think you can fix it by making sure you are using the precisely correct version of the Android NDK (android-ndk-r10e).
Also make sure that you set the environment variables and stuff done right.
(For what it's worth I'm stuck on later steps, but hopefully this should help you get passed this particular issue)
You have to change your path to ANDROID_NDK to run gradle command locally.
export ANDROID_NDK=/Users/your_unix_name/android-ndk/android-ndk-r10e
In my case, I put NDK file at /Users/tomo/temp/android-ndk-r10e
so
export ANDROID_NDK=/Users/tomo/temp/android-ndk-r10e
Or if you do not want to change ANDROID_NDK, you can update ReactAndroid/build.gradle
def findNdkBuildFullPath() {
// we allow to provide full path to ndk-build tool
if (hasProperty('ndk.command')) {
return property('ndk.command')
}
// or just a path to the containing directory
if (hasProperty('ndk.dir')) {
def ndkDir = property('ndk.dir')
return new File(ndkDir, getNdkBuildName()).getAbsolutePath()
}
// ** Add below. should be before if (System.getenv('ANDROID_NDK') clause **
Properties properties = new Properties()
properties.load(project.rootProject.file('ReactAndroid/local.properties').newDataInputStream())
if (properties.hasProperty('ndk.dir')) {
def ndkDir = properties.getProperty('ndk.dir')
return new File(ndkDir, getNdkBuildName()).getAbsolutePath()
}
if (System.getenv('ANDROID_NDK') != null) {
def ndkDir = System.getenv('ANDROID_NDK')
return new File(ndkDir, getNdkBuildName()).getAbsolutePath()
}
def ndkDir = android.hasProperty('plugin') ? android.plugin.ndkFolder :
plugins.getPlugin('com.android.library').hasProperty('sdkHandler') ?
plugins.getPlugin('com.android.library').sdkHandler.getNdkFolder() :
android.ndkDirectory.absolutePath
if (ndkDir) {
return new File(ndkDir, getNdkBuildName()).getAbsolutePath()
}
return null
}
then update ReactAndroid/local.properties
ndk.dir=/Users/tomo/temp/android-ndk-r10e
sdk.dir=/Applications/sdk
and Run app from Android Studio
for React Native 7.0
try either :
rm -rf node_modules && yarn install (worked for me)
or
These steps:
Close Android Studio
Add android.disableAutomaticComponentCreation=true in android/gradle.properties
Reopen project and build.

Entity Framework Migrations - How to create a Unit Test to Ensure Migrations Model is up to Date?

I am using continuous integration with TeamCity, NUnit, and Git. I recently migrated (pardon the pun) from FluentMigrator to Entity Framework Migrations. I primarily did this to take advantage of the scaffolding functionality therein.
However, it is potentially possible to check in some changes to source control without having first scaffolded the changes into migrations (imagine the scenario where the application was not run before committing and pushing the commit). I am using a pre-tested commit workflow, so I would like to detect this problem in the pre-test rather than waiting until calling migrate.exe (which would be too late in my workflow and break the "green repository").
My question is, how to create a unit/integration test to detect when the migrations model doesn't match the context model so I can fail the build before attempting to migrate? Do note that I expect it not to match the database and would prefer not to access the database from the test.
I tried this approach:
[Test]
public void CheckWhetherEntityFrameworkMigrationsContextIsUpToDate()
{
Assert.DoesNotThrow(() =>
{
CallDatabase();
});
}
private void CallDatabase()
{
using (var ctx = new MyContext("SERVER=(local);DATABASE=MyDatabase;Integrated Security=True;"))
{
var tenant = (from t in ctx.Tenant
select t).FirstOrDefault();
}
}
But this will always fail when there are pending migrations (rather than just in the case where the migrations model is not in sync with the context model, which is what I am after).
Update
I have added a work item on the EntityFramework project for this issue. Hopefully, they will look into adding a way to do this.
In case anybody finds this useful, I test migrations by running all of them against a test database, using the following code:
[TestClass]
public class MigrationsTests
{
[TestMethod]
public void RunAll()
{
var configuration = new Configuration();
var migrator = new DbMigrator(configuration);
// back to 0
migrator.Update("0");
// up to current
migrator.Update();
// back to 0
migrator.Update("0");
}
}
This tests all Up and Down migrations, as well as detecting pending changes when automatic migrations is turned off.
NOTE: Make sure you run this against a test database. In my case the test project's app.config has the connectionString to the test database (just a local SQLExpress instance).
Here is some code that will check whether all model changes have been scaffolded to migrations or not.
bool HasPendingModelChanges()
{
// NOTE: Using MigratorScriptingDecorator so changes won't be made to the database
var migrationsConfiguration = new Migrations.Configuration();
var migrator = new DbMigrator(migrationsConfiguration);
var scriptingMigrator = new MigratorScriptingDecorator(migrator);
try
{
// NOTE: Using InitialDatabase so history won't be read from the database
scriptingMigrator.ScriptUpdate(DbMigrator.InitialDatabase, null);
}
catch (AutomaticMigrationsDisabledException)
{
return true;
}
return false;
}
I wanted the best of all the answers given here so far so here's what I've come up with:
[TestClass()]
public class MigrationsTests
{
[TestMethod()]
public void MigrationsUpDownTest()
{
// Unit tests don't have a DataDirectory by default to store DB in
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());
// Drop and recreate database
BoxContext db = new BoxContext();
db.Database.Delete();
var configuration = new Migrations.Configuration();
var migrator = new DbMigrator(configuration);
// Retrieve migrations
List<string> migrations = new List<string>;
migrations.AddRange(migrator.GetLocalMigrations());
try
{
for (int index = 0; index < migrations.Count; index++)
{
migrator.Update(migrations[index]);
if (index > 0) {
migrator.Update(migrations[index - 1]);
} else {
migrator.Update("0"); //special case to revert initial migration
}
}
migrator.Update(migrations.Last());
}
catch (SqlException ex)
{
Assert.Fail("Should not have any errors when running migrations up and down: " + ex.Errors[0].Message.ToString());
}
// Optional: delete database
db.Database.Delete();
}
[TestMethod()]
public void PendingModelChangesTest()
{
// NOTE: Using MigratorScriptingDecorator so changes won't be made to the database
var migrationsConfiguration = new Migrations.Configuration();
var migrator = new DbMigrator(migrationsConfiguration);
var scriptingMigrator = new MigratorScriptingDecorator(migrator);
try
{
// NOTE: Using InitialDatabase so history won't be read from the database
scriptingMigrator.ScriptUpdate(DbMigrator.InitialDatabase, null);
}
catch (AutomaticMigrationsDisabledException)
{
Assert.Fail("Should be no pending model changes/migrations should cover all model changes.");
}
}
}
Couple things worth noting:
You need to install Entity Framework in your test project
You need to add [assembly: InternalsVisibleTo("MyTestsProject")] to the top of your Configuration class
You need to specify an Entity Framework connection string in App.config that is only for test project since database will be deleted and recreated frequently - if running on build machine keep in mind that parallel runs could result in conflicts so you may want to change string per build
I think this works better than Pablo Romeo's code. This upgrades and then downgrades one step again to catch missing items in the downgrade scripts.
[TestFixture]
class MigrationTest
{
[Test]
public void RunAll()
{
var configuration = new Configuration();
var migrator = new DbMigrator(configuration);
// Retrieve migrations
List<string> migrations = new List<string> {"0"}; // Not sure if "0" is more zero than the first item in list of local migrations
migrations.AddRange(migrator.GetLocalMigrations());
migrator.Update(migrations.First());
// Doe een stapje naar voren, en een stapje terug (www.youtube.com/watch?v=2sg1KAxuWKI)
// (Dutch pun) meaning: take a small step forward, and a small step back ;)
for (int index = 0; index < migrations.Count; index++)
{
migrator.Update(migrations[index]);
if (index > 0)
migrator.Update(migrations[index - 1]);
}
migrator.Update(migrations.Last());
migrator.Update(migrations.First());
}
}
EF Core has a pretty straight forward method:
myDbContext.Database.Migrate();

XmlDeserialization fails in medium trust level

We have our site hosted in medium trust level and the hosting provider has refused to give us full trust. Our code tries to deserialize code using following code snippet but fails with the reflectionpermission error. Upon debug I get "There is an error in XML document (71, 6)." error. It works perfectly fine in full trust. Please someone advice how I can solve this problem before we decide to move to full trust hosting provider.
public static T Decrypt<T>(Stream stream)
{
Rijndael rij = Rijndael.Create();
rij.Key = key;
rij.IV = iv;
T obj = default(T); // assigns null if T is a reference type, or 0 (zero) for value types
using (CryptoStream cs = new CryptoStream(stream, rij.CreateDecryptor(), CryptoStreamMode.Read))
{
using (GZipStream zs = new GZipStream(cs, CompressionMode.Decompress))
{
XmlSerializer xs = new XmlSerializer(typeof(T));
obj = (T)xs.Deserialize(zs);
zs.Close();
}
cs.Close();
}
return obj;
}
Open the project properties and set "Generate serialization assembly" to "on". This will make the compiler generate serialization assemblies at compile-time instead of on the fly. Just make sure to deploy the serialization assemblies.