Weird .net 4.0 exception when running unit tests - unit-testing

I am receiving the following exception when trying to run my unit tests using .net 4.0 under VS2010 with moq 3.1.
Attempt by security transparent method
'SPPD.Backend.DataAccess.Test.Specs_for_Core.When_using_base.Can_create_mapper()'
to access security critical method
'Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(System.Object)'
failed.
Assembly
'SPPD.Backend.DataAccess.Test,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' is marked with
the
AllowPartiallyTrustedCallersAttribute,
and uses the level 2 security
transparency model. Level 2
transparency causes all methods in
AllowPartiallyTrustedCallers
assemblies to become security
transparent by default, which may be
the cause of this exception.
The test I am running is really straight forward and looks something like the following:
[TestMethod]
public void Can_create_mapper()
{
this.SetupTest();
var mockMapper = new Moq.Mock<IMapper>().Object;
this._Resolver.Setup(x => x.Resolve<IMapper>()).Returns(mockMapper).Verifiable();
var testBaseDa = new TestBaseDa();
var result = testBaseDa.TestCreateMapper<IMapper>();
Assert.IsNotNull(result); //<<< THROWS EXCEPTION HERE
Assert.AreSame(mockMapper, result);
this._Resolver.Verify();
}
I have no idea what this means and I have been looking around and have found very little on the topic. The closest reference I have found is this http://dotnetzip.codeplex.com/Thread/View.aspx?ThreadId=80274 but its not very clear on what they did to fix it...
Anyone got any ideas??

In the AssemblyInfo.cs of the referenced project add this following line
[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]

MSDN: "The .NET Framework version 4 introduces new security rules that affect the behavior of the AllowPartiallyTrustedCallersAttribute attribute (see Security-Transparent Code, Level 2). In the .NET Framework 4, all code defaults to security-transparent, that is, partially trusted. However, you can annotate individual types and members to assign them other transparency attributes."
Haven't come across this myself, but perhaps you have imported somehing from a 3.5 project.
Check out these links:
Security Changes in the .NET Framework 4
Security-Transparent Code, Level 2
AllowPartiallyTrustedCallersAttribute Class

This has been fixed in the latest version of Moq (it was a fix in DynamicProxy actually).
Please give the latest v4 Beta a try.
http://moq.me

Related

WinUI 3 Desktop XAML Databinding - WinRT originate error - 0x8001010E when the Property is changed

I am following the BookStore data binding example, documented at XAML controls; bind to a C++/WinRT property, up to and including the "Bind the button to the Title property" section.
My starting point is a new "Blank App, Packaged (WinUI 3 in Desktop)" project in Visual Studio.
[EDIT] Starting from a "Blank App (C++/WinRT)" project, which is for UWP apps, works perfectly. The problem persists with "WinUI 3 in Desktop" projects.
The initial data binding works and the button content L"Atticus" is read from the BookSku title property. However calling MainViewModel().BookSku().Title(L"To Kill a Mockingbird"); in the click handler, as directed in article, throws the exception
Exception thrown at 0x00007FFC801B4ED9 (KernelBase.dll) in BookStore.exe: WinRT originate error - 0x8001010E : 'The application called an interface that was marshalled for a different thread.'.
Stepping through the code, the call
m_propertyChanged(*this, Windows::UI::Xaml::Data::PropertyChangedEventArgs{ L"Title" });
in void BookSku::Title(hstring const& value) is where the exception is thrown from within.
I can change the button content manually, not through the binding property.
The first example in the Data binding in depth article describes a very similar, though slightly less complicated, data binding scenario. It throws the same exception.
I am using latest Microsoft.Windows.CppWinRT version 2.0.210825.3 and Windows App SDK version 0.8.3
This issue #4547 was the key to figuring out the solution. You need to use the Microsoft namespace, not Windows. For documentation purposes this is what the BookSku.idl file should look like:
// BookSku.idl
namespace Bookstore
{
runtimeclass BookSku : Microsoft.UI.Xaml.Data.INotifyPropertyChanged
{
BookSku(String title);
String Title;
}
}
The application called an interface that was marshalled for a different thread
The problem is you update the property in the no-uithread, so it will throw the above exception, you could use the following to go back to ui-thread before updating the property.
co_await winrt::resume_foreground(Dispatcher(), CoreDispatcherPriority::Normal);
For more detail please refer to document here.

In Unity3d test scripts, how do I call a static function from another class?

I have two files in a Unity3d project. One is a test script that runs in edit mode. The other is a single class with static functions that I'd like to call from the test scripts.
here's my test script:
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
public class NewTestScript
{
[Test]
public void TestAnotherStaticFunction()
{
int a = NewBehaviourScript.FunctionUnderTest(1);
int b = 1;
// Use the Assert class to test conditions.
Assert.IsTrue(a == b);
}
}
here's my function under test:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
/// <summary>
/// the stupidest function in the world,
/// used to verify tests.
/// </summary>
public static int FunctionUnderTest(int a)
{
return a;
}
}
This gives me the error from the Unity compiler (I'm not building outside of Unity):
Assets/TestS/NewTestScript.cs(12,17): error CS0103: The name `NewBehaviourScript' does not exist in the current context
These are running in edit-mode.
I've tried adding and removing the SuperTestNameSpace namespace from the function under test and the calling code.
I've attempted adding/removing files from the .asmdef file that was autogenerated by unity, although this usually leads to other compile errors.
My previous unit test experience is largely in Visual Studio or VSCode, and I'm trying to get my unity3d test experience to match my prior test environment experiences.
Is there a fundamentally limited functionality in the edit-mode tests, or am I missing something stupid?
Further elaboration on the assemblies involved. It looks like there are two assemblies at play here: Assembly-CSharp.dll contains my code under test and TestS.dll contains my testing code. I believe my questions boils down to: how do I add a reference from the TestS.dll assembly to the Assembly-CSharp.dll. I'd know how to do this in Visual Studio (either via the context menu in VS or directly editing the csproj file), however I don't see how to do it in Unity3d. Any edit I make to the csproj file is frequently overwritten by unity, and while there is a 'references' section in the inspector (see picture) I can't add Assembly-CSharp.dll as a reference.
These are the inspector settings for TestS.asmdef. While there's an option to add references, I can't add a reference to Assembly-CSharp.dll, which is where my code-under-test lives.
Ok, I figured this out. There were two things going on:
Editor tests need to be underneath a folder called editor. It's really annoying that the unity editor doesn't do this for you.
You need to have an assembly definition for the code under test and add a reference from the test code to the newly created assembly definition. This must be done in the Unity editor UI.
by default, unity adds your script code to an assembly called Assembly-CSharp.dll, and, for reasons unknown, this assembly isn't referenced by my edit mode test code. I'm not sure if this is a bug in Unity or if it's by design, but explicitly creating and referencing the assembly definition has cleared things up.
The main issue is currently you are trying to call the
NewBehaviourScript(1);
constructor which does not exist...
instead of the method
using SuperTestNameSpace;
//...
NewBehaviourScript.FunctionUnderTest(1);
or alternatively with the namespace in the call directly
SuperTestNameSpace.NewBehaviourScript.FunctionUnderTest(1);
Also make sure the filename matches exactly the class name. So in your case it should be
NewBehaviourScript.cs
Note that the .cs is not printed by Unity in the Project view so there it should say NewBehaviourScript.
Why does it not compile with the using SuperTestNameSpace;? What is the error?
If that exception
Assets/TestS/NewTestScript.cs(14,17): error CS0103: The name `NewBehaviourScript' does not exist in the current context
is only shown in VisualStudio but the script compiling fine in Unity especially after adding a new script it helps to simply close and restart VS.
In some cases it also helps to close Unity and VS, remove all files and folders except Assets and ProjectSettings (and if you are under version control anything that belongs to it like e.g. .git, .gitignore, .gitattributes etc) in particular delete the Library, .vs folder and all .csproj and .sln files.
Than open Unity again and let it recompile everything.
Make sure the file that contains your NewBehaviourScript class IS NOT inside an Editor folder.
Move both the scripts in the Assets (root) folder and try again.

AWS and Changes in Swift 3

After the Swift 3 update, I'm having some trouble getting my app to compile. Most of the errors are pretty simple to fix, but I'm running into a few in particular with AWS. Is there some sort of updated AWS SDK for Swift 3? I've tried to look it up, but haven't found one. In any case, the two main errors I'm having trouble resolving are as follows:
"Type 'IdentityProviderManager' does not conform to protocol AWSIdentityProviderManager." This is for a class I created following a tutorial to set up logins through AWS Cognito. The code is:
class IdentityProviderManager: NSObject, AWSIdentityProviderManager{
var tokens : [NSString : NSString]?
init(tokens: [NSString : NSString]) {
self.tokens = tokens
}
#objc func logins() -> AWSTask<AnyObject> {
return AWSTask(result: tokens as AnyObject)
}
}
In the AWS documentation for AWSIdentityProviderManager, it says that the only required function is logins, which I have. Is there a simple way to resolve this that I'm missing?
The other error is in my LoginViewController class: "Type 'LoginViewController' does not conform to protocol 'AWSCognitoIdentityPasswordAuthentication'." Here the issue seems a bit more clear, since the documentation says that getPasswordAuthenticationDetails() is a required method and XCode seems to have changed this method to getDetails() when updating to Swift 3, unless I'm mistaken and it wasn't there to begin with or something. In any case, autocomplete doesn't give me the original method and I can't seem to make the class conform to the protocol.
Apologies if the answer is already in documentation somewhere, but as far as I can tell it seems like the AWS SDK (at least the version that I have) is somehow incompatible with Swift 3. Is there something I can do to resolve these errors?
Nevermind, it turned out XCode just wasn't showing me the option to make the changes I needed. The automatic fix implemented slightly different versions of the required functions and everything ended up working.

Google Play Services C++ / Run UI on second activity using IntentHandler

I am developing a mobile game using Cocos2D-x engine for android platform and i want to integrate GPGS on it.
I achieved to show leaderboards, but there is a little annoying problem. When leaderboard is visible, if i go background and then come back to app, the gamescene goes to black. I think opengl context being released and doesnt restore again. In my opinion running leaderboard on same activity causes this, the game engine cant understand whats happening there. Whatever, because of this I want to run leaderboard (and also all GPGS things) on a new activity using intent.
Google likes "Providing"
In the reference documents of Google Play Game Services C++ SDK, there is a few unclear/fuzzy explanation about using SetOptionalIntentHandlerForUI method.
"Provide a function that can start a provided UI intent at any point, using startActivityForResult."
What is the mean of "Providing"? What is a provided Intent? How will I use startActivityForResult method? Unfortunately, "using" and "providing methods" are not clear expressions for coding. There is no sample about
using this method in the documents of GPGS for C++. Eventually,
Google's document is so poor and
there is no useful information on the internet. If someone from Google helps me, I will be so happy.
As i understand, I wrote the code like this. But it gives error when starting.
AppActivity.java
public void runGPGSActivity(Intent i) {
startActivityForResult(i,100);
}
AndroidPlatformConfiguration.h (From C++ gpg lib)
typedef std::function<void(jobject)> IntentHandler;
AndroidPlatformConfiguration &SetOptionalIntentHandlerForUI(
IntentHandler intent_handler);
main.cpp (JNI binding, the working code, GPGS runs on same activity )
gpg::AndroidPlatformConfiguration platform_configuration;
platform_configuration.SetActivity(activity);
StateManager::InitServices( ...
main.cpp (JNI binding, GPGS must be run on new activity )
gpg::AndroidPlatformConfiguration platform_configuration;
jclass activityClass = env->FindClass("org/cocos2dx/cpp/AppActivity");
jmethodID jIntentHandlerMethodID = env->GetMethodID(activityClass,"runGPGSActivity","(Landorid/content/Intent;)V");
jobject jIntentHandler = env->NewObject(activityClass, jIntentHandlerMethodID);
gpg::AndroidPlatformConfiguration::IntentHandler mIntentHandler; /*= [](jobject mjIntentHandler){};*/
std::function<void(jobject)> intentHandler = std::bind(mIntentHandler,jIntentHandler);
platform_configuration.SetOptionalIntentHandlerForUI(intentHandler);
platform_configuration.SetActivity(activity);
StateManager::InitServices(
There is no build error, but the application crashes when launching.
03-24 14:12:24.301: A/libc(21352): Fatal signal 6 (SIGABRT) at
0x00005368 (code=-6), thread 21352 (main)
And some links about this issue:
IntentHandler reference
StartActivityForResult reference
/// Thank you in advance. ///
...Yeah I solved the problem, but didn't use IntentHandler method.
I was using this code in my app, to show weekly leaderboard data.
gameServices->Leaderboards().ShowUIBlocking(leaderboardId,gpg::LeaderboardTimeSpan::WEEKLY);
But return value is not void, it is UIStatus (whatever it is)
I've reverted back to this code, app is not going to black screen now. This method returns void, I think I have to catch some callbacks when using ShowUIBlocking method, with that UIStatus thing.
gameServices->Leaderboards().ShowUI(leaderboardId);
But now, I can't benefit from timespan feature of leaderboards.
I am going to research how it can be used. There is no problem for now. But, documentation of SetOptionalIntentHandlerForUI must be written more explicit, for programmers who want to use it.

ExpectedException on TestMethod Visual Studio 2010

Today I upgraded my solution with all the underlying projects from VS2008 to VS2010. Everything went well except for my unit tests.
First of all only the web projects had as target framework .NET 4. All the other projects still had .NET 3.5. I changed them all to .NET 4.
Now when I debug my unit tests it breaks on every exception. In 2008 it just wouldn't pass and tell me that an exception occurred. Even when I have the ExpectedException attribute defined it stops debugging on every exception.
And example of one of my tests:
[TestMethod]
[ExpectedException(typeof(EntityDoesNotExistException))]
public void ConstructorTest()
{
AddressType type = new AddressType(int.MaxValue);
}
The EntityDoesNotExistException is a custom exception and inherits Exception.
Edit
I looked at the Exceptions settings (ctrl+alt+e) in 2008 and 2010. In both versions the settings are the same. However in 2008 the debug doesn't break when I have the ExpectedException attribute. In 2010 it does break.
Gerrie pointed me in the right direction:
Press Ctrl-Alt-E
Open the Common Language Runtime Excepions Node
Click Add
Type Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException
Make sure that both checkboxes are unchecked.
This will get rid of the break on failed Asserts, but the test will still break when you have set an ExpectedException.
I was the one that set the 100 bonus for this, so some upvotes would be appreciated ;-)
According to Microsoft, this is not a bug, it's "by design":
http://connect.microsoft.com/VisualStudio/feedback/details/511897/expectedexception-still-causes-debugging-to-break-with-exception-was-unhandled-by-user-code
Press Ctrl+Alt+E and check the break on exception setting for CLR exceptions. If this is set to true then the behavior you described will occur.
A Microsoft support guy told me to use Ctrl-F5 (start without debugging) when running my unit tests, and that seems to work.
Another thing to try is to go to Tools|Options|Debugging
and un-check the "Enable Just My Code" option.
Make sure your reference to Microsoft.VisualStudio.QualityTools.UnitTestingFramework is Version 10.0.0.0.
If it is version 9.0.0.0 this problem will occur in Visual Studio 2010.
Hope this helps. If people still have this problem.
I second what rlandster said. Clearing the "Enable Just My Code" debugging option fixed this for me. It fixed both breaking on assers and breaking on expected exceptions. There's a little more detail on this at http://social.msdn.microsoft.com/Forums/en/vsdebug/thread/25bdf149-5133-4f47-bbf2-1d4ca638fee9.
I've had the same issue, but finally managed to get it working. Not really sure how but here's a list of things I did between it not working to when it started working again.
Converted the project being tested to .NET 4
Turned off CodeCoverage
Turned CodeCoverage back on again
Did a RebuildAll on the test project
Not sure which bit fixed it though. Anyway, hope this helps!
I ended up changing my tests to this form to avoid the breaking. Not ideal:
[TestMethod]
public void Guid()
{
try
{
Guid g = new Guid("myguid'123'");
}
catch( FormatException fe)
{
return; // expected exception - pass
}
Assert.Fail(); // exception not thrown - fail
}