Unity Container - ResolutionFailedException when removing covariance - unity-container

I have an a unity registration that works just fine with the out covariance, but once I remove it, I get the error
"ClassName": "Microsoft.Practices.Unity.ResolutionFailedException",
"Message": "Resolution of the dependency failed, type = \"REDACTED.IChatTranscriptBc1[REDACTED]\", name = \"REDACTED\".\r\nException occurred while: Calling constructor Microsoft.Practices.Unity.InterceptionExtension.PolicyInjectionBehavior(Microsoft.Practices.Unity.InterceptionExtension.CurrentInterceptionRequest interceptionRequest, Microsoft.Practices.Unity.InterceptionExtension.InjectionPolicy[] policies, Microsoft.Practices.Unity.IUnityContainer container).\r\nException is: ArgumentException - Interface not found.\r\n-----------------------------------------------\r\nAt the time of the exception, the container was:\r\n\r\n Resolving REDACTED.ChatTranscriptBc,REDACTED (mapped from REDACTED.IChatTranscriptBc1[REDACTED], REDACTED)\r\n Resolving Microsoft.Practices.Unity.InterceptionExtension.PolicyInjectionBehavior,(none)\r\n Calling constructor Microsoft.Practices.Unity.InterceptionExtension.PolicyInjectionBehavior(Microsoft.Practices.Unity.InterceptionExtension.CurrentInterceptionRequest interceptionRequest, Microsoft.Practices.Unity.InterceptionExtension.InjectionPolicy[] policies, Microsoft.Practices.Unity.IUnityContainer container)\r\n"
My interface when it works:
public interface IChatTranscriptBc<out TTranscript>
where TTranscript : Transcript
My interface when it breaks
public interface IChatTranscriptBc<TTranscript>
where TTranscript : Transcript
Literally, the only change is my removal of "out." I've rebuilt all my libraries, restarted my computer, everything. Any idea why the removal of the covariance breaks unity?

I figured it out. I was resolving to IChatTranscript and the concrete class it matched to did not match that exact definition (it was using an implementation of Transcript, not Transcript itself). Bubbling up, it threw that error.

Related

Laravel 5.7 testing with RefreshDatabase trait throws ErrorException: Trying to access array offset on value of type int

so as I stated in the title, I am working on Laravel 5.7 project and am making first tests in this application (big system). We did not make any tests in here yet, so this problem is the first time here.
For every test, this is how the controller uses the trait
use RefreshDatabase;
protected function setUp()
{
parent::setUp();
$this->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class);
$this->withoutExceptionHandling();
}
As you can see, I am just trying to use the trait to refresh the DB after the tests are done.
The problem arises when I call to execute the tests.
ErrorException: Trying to access array offset on value of type int
C:\laragon\www\demi\systems\damaro\vendor\symfony\console\Input\ArrayInput.php:135
C:\laragon\www\demi\systems\damaro\vendor\symfony\console\Input\Input.php:55
C:\laragon\www\demi\systems\damaro\vendor\symfony\console\Command\Command.php:214
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Console\Command.php:170
C:\laragon\www\demi\systems\damaro\vendor\symfony\console\Application.php:886
C:\laragon\www\demi\systems\damaro\vendor\symfony\console\Application.php:262
C:\laragon\www\demi\systems\damaro\vendor\symfony\console\Application.php:145
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Console\Application.php:89
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Console\Application.php:188
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:250
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Foundation\Testing\PendingCommand.php:136
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Foundation\Testing\PendingCommand.php:218
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithConsole.php:55
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Foundation\Testing\RefreshDatabase.php:55
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Foundation\Testing\RefreshDatabase.php:18
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:104
C:\laragon\www\demi\systems\damaro\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:71
This is the whole trace.
Some solutions I found are:
composer update - not an option, because the project is in production
disable telescope package in phpunit.xml - did not work
I also tried installing telescope package - did not work as well
Do you have any idea?
So I have not found an answer to this question, but I have found a workaround.
Instead of using RefreshDatabase trait I decided to use DatabaseTransactions trait.

How do you wire up states and flows in separate CorDapps for ScheduableState/ScheduableFlow

We have been following the same framework as in the template (Corda v1.0 onwards) to separate the ContractAndStates and Flow into 2 CorDapps in our development work but ran into some issues when we are using SchedulableFlow. It seems that the SchedulableState and the SchedulableFlow needs to be in the same CorDapp because of the dependencies. We are following the heartbeat CorDapp example to create our ScheduabeState for a cyclic flow to be initiated (https://github.com/joeldudleyr3/heartbeat).
override fun nextScheduledActivity(thisStateRef: StateRef, flowLogicRefFactory: FlowLogicRefFactory): ScheduledActivity? {
// A heartbeat will be emitted every second.
// We get the time when the scheduled activity will occur in the constructor rather than in this method. This is
// because calling Instant.now() in nextScheduledActivity returns the time at which the function is called, rather
// than the time at which the state was created.
return ScheduledActivity(flowLogicRefFactory.create(HeartbeatFlow::class.java, thisStateRef), nextActivityTime)
As a result of this dependency in the ScheduableState (see above), we would have to create the flow in the same CorDapp as in the ContractAndState, which we have decided not to do. Rather, our workaround is to do the scheduling on the spring backend for the time-being.
Currently to add dependencies to the flow CorDapp, you add to the flow CorDapp project, the ContractAndState in the build.gradle. To make the ContractAndState depend on the flow, you can't add the dependency into its build.gradle else it creates a circular reference. The only way we have found is still to add to the ContractAndState CorDapp project the flow that the ScheduableState is dependent on, so its not really working if we follow the template. Are there workarounds or have we not wire-up the dependencies correctly?
There is a special FlowLogicRefFactory.create method exactly for this use-case.
You are using fun create(flowClass: Class<out FlowLogic<*>>, vararg args: Any?): FlowLogicRef, which requires a FlowLogic class.
Instead, you can use fun create(flowClassName: String, vararg args: Any?): FlowLogicRef, which takes a fully-qualified class name.

Autofac SingleInstance() and Xamarin Forms

To start, let me say that I have read several questions here about SingleInstance, but still cannot find a direct answer that helps me. That said, I apologize if I missed anything.
Here's my question:
I am building a Xamarin Forms app for iOS and Android. I have a single AppInitializer class in a PCL where I register all of my interface dependencies using Autofac. I then assign the Container from the builder as a static property on the app class. The problem I encounter is that while I'm registering everything with .SingleInstance(), I'm not actually getting a single instance.
Init Logic Example:
var builder = new ContainerBuilder();
builder.RegisterType<ErrorHandler>().SingleInstance().As<IErrorHandler>();
…
builder.RegisterType<MemberViewModel>().SingleInstance().As<IMemberViewModel>();
…
AppContainer.Current = builder.Build();
I am letting Autofac handle resolving interfaces in my constructors. For example:
public MemberViewModel(ISettingsViewModel settings, IErrorHandler errorHandler, …) : base(settings, errorHandler){…}
I then use said model on a page as below:
Example page usage:
public ProfilePage()
{
InitializeComponent();
var displayModel = Model.CurrentMember;
…
}
…
**public IMemberViewModel Model =>
AppContainer.Current.Resolve<IMemberViewModel>();**
In this example I set Model.CurrentMember's properties immediately before arriving on this page. I've set breakpoints and know for a fact this is happening. However, when I resolve the instance of the model, the properties on CurrentMember are null.
Am I doing something wrong here or have I encountered a bug?
-Edit-
Made it clear that I'm using Autofac.
-Edit 2-
Adding more detail.
My implementation of the IMemberViewModel class has various properties on it, including an observable object called current member. It is declared as below:
public class MemberViewModel : ViewModelBase, IMemberViewModel
{
…
(see constructor above)
…
public MemberDisplay CurrentMember =>
m_CurrentMember ?? (m_CurrentMember = new MemberDisplay())
On the implementation of IMemberViewModel I have a method that sets the various properties on CurrentMember.
The order of operations is this:
The end user taps an image for a member. This fires a command on the (theoretically) singleton instance of the IMemberViewModel implementation. This command executes an async task that awaits an async call to the API to load the data for that member. After that data is loaded and the properties set on CurrentMember, the app navigates to the profile screen. The profile screen resolves IMemberViewModel (per above).
Expected Behavior:
The properties on CurrentMember from the resolved instance of IMemberViewModel are set to the values that have just been set from the load data method. This expectation arises from assuming that there is a single instance of IMemberViewModel.
Actual Behavior:
The CurrentMember's properties are at their default values, i.e. string.Empty, 0, null, etc.
The odd thing here is that this doesn't happen to every model. I have a message model that I am resolving in the same manner on the same screen and it seems to be fine.
This issue turned out to be caused by the way we were going about initializing everything. For posterity's sake, I will give a brief breakdown of what was happening and what I did to prevent it.
Previous App Flow:
App opens & constructor is called. This calls into the initialization routine above.
User logs in.
First instance of IMemberViewModel resolved using static container.
A message pops up asking the user for Push Notifications Permissions
When this happens, the app OnSleep is called (iOS)
After the user selects an answer, OnResume is called.
OnResume calls initialization routine
New container created.
Call to load data happens on old container, new pages reference new container.
Issue arises as described above.
Correction to the flow:
First, from what I can tell the init calls do not need to be made on resume and/or start if made in the app constructor. If the app is "killed" because other apps need the memory space, a fresh version of the app will be created on next launch (see the Android Activity Lifecycle and the iOS App Lifecycle).
Second, because I'm paranoid and because it can't hurt, in the app init routine I am now checking to determine whether the container exists and whether the interface is already registered.
public static void Init(ISetup setup)
{
if (Container != null && IsModelRegistered()) return;
RegisterDependencies(setup);
…
}
private static bool IsModelRegistered()
{
return Container.IsRegistered<IMemberViewModel>();
}

warning: "Cannot find file '/3' locally. To fix it set server name by environment variable PHP_IDE_CONFIG and restart debug session."

Every time I step into the method (prepareStatusFilterQuery()) while unit testing with debug I got warning and debugger not stepping into the method. Warning:
Cannot find file '/3' locally. To fix it set server name by
environment variable PHP_IDE_CONFIG and restart debug session.
Other than this case debugger works fine.
This happens when you try to step into the code of a mock object.
There is no solution for it because the mock objects are instances of classes that are created during the execution of the test.
PHPUnit MockObjects uses reflection to gather information about the class you ask it to mock (the names and arguments of the public methods) then it generates the PHP code of a new class (that extends the mocked class) and runs it using eval().
The debugger is actually stepping into the method but PhpStorm cannot display the source code because there is no source code for it. Keep using the "Step Into" command and at some point the control will go back to code (of PHPUnit) whose source code is loaded from a file and PhpStorm can find it.
Just encountered this error. In my case it was caused by the method missing the private keyword:
class SomeClass {
function some_function_name () {
}
}
Should look like:
class SomeClass {
private function some_function_name () {
}
}

Customizing failure reporting in TestNG

Background:
I have created a basic playground project that contains:
A testLogin.java file that contains:
a. testng package imports (org.testng.*)
b. selenium webdriver imports (org.openqa.selenium.*)
c. 5 test-methods with testng annotations:
#Test(groups={"init"})
public void openURL()
Contains webdriver code to initiate the webdriver and open a chrome >instance with a given url.
#Test(dependsOnGroups={"init"})
public void testLogin()
Contains webdriver code to:
1. Locate username password text-input elements, enter the username password from a properties file.
2. Locate the "log in" button and click the button to log-in
3. Manage a login-forcefully scenario if someone else has already logged in using the credentials.
#Test(dependsOnMethods={"testLogin"})
public void testPatientsScheduleList()
Contains webdriver code to check if any patients have been scheduled. If yes, then fetch the names and display in console.
#Test()
public void testLogout()
Contains webdriver code to locate the logout button and click on the button to logout of the app.
#AfterTest()
public void closeConnection()
Contains webdriver code to dispose the webdriver object and close the chrome instance.
Currently I am simply running the test script wrapped as testng methods from ANT and a testng-xslt report gets generated.
Issues:
1. Performing validations against every line of code of webdriver script in a test method:
I know:
1. Selenium webdriver script contains API methods (findElement() and others.) that throw exceptions as a result of a default assertion/validation they perform. These exceptions show up in the generated report when a test-method fails.
2. TestNG provides Assert class that has many assertion methods but I have not yet figured out how can i use them to perform validation/assertions against every line of code of webdriver script. I tried adding assertion methods after every line of webdriver script code. What appeared in the output was just an AssertionError exception for a testmethod.
2. Failing a certain test method which gets passed due to try.. catch block.
If I use a try catch block around a set of 2 or more test drive script steps, and if a test-case fails in any of the steps (script line) then the try..catch block handles it thereby showing the test-method as "passed" in the execution report, which actually failed.
3. Creating a custom report which will show desired test execution results and not stack-traces!
When I execute the above script, a testng-xslt report gets generated that contains pass/fail status of each test method in a test-suite (configured in testng.xml).
The test-results only give me whether a test-method has passed or failed and provides an exception's stack-trace which really doesn't provide any helpful information.
I don't want such abstract level of test execution results but something like:
Name | Started | Duration | What-really-went-wrong (Failure)
Can anyone please suggest/ give some pointers regarding:
1. How can I perform validation/assertion against every line of code of webdriver script in a test-method without writing asserts after every script line?
2. How can I fail a certain test method which gets passed due to try catch block?
3. How can I customize the failure reporting so that I can send a failure result like "Expected element "button" with id "bnt12" but did not find the element at step 3 of test-method" to testng's reporting utility?
4. In the testng-xslt report I want to display where exactly in the test-method a failure occurred. So for example if my test-method fails because of a webelement = driver.findElement() at line 3 of a test-method, I want to display this issue in the test-report in the "What-really-went-wrong" column. I have read about testng testlisteners TestListenerAdapter / ITestListener/ IReporter but I don't understand how to use them after checking testng's javadocs.
5. Also, I have to implement PageObject pattern once I am done with customizing the test report. Where would be the right place to perform assertions in a page-object pattern? Should assertions be written in the page object test methods or in the higher level test methods that will use the PageObject classes?
P.S: I am completely new to testng framework and webdriver scripting. Please bear with any technical mistakes or observation errors if any in the post.
How can I perform validation/assertion against every line of code of webdriver script in a test-method without writing asserts after
every script line?
I dont think so. It is the assertions that does the comparison. So u need it.
How can I fail a certain test method which gets passed due to try catch block?
try-catch will mask the assertion failure.(because on assertion failure, an assertion exception is thrown, so if your catch block is like (catch(Exception e)) Assertion failures wont escape the catch block.
How can I customize the failure reporting so that I can send a failure result like "Expected element "button" with id "bnt12" but did
not find the element at step 3 of test-method" to testng's reporting
utility?
You need to use test listeners . TestNG TestListenerAdapter is a good start
Also, I have to implement PageObject pattern once I am done with
customizing the test report. Where would be the right place to perform
assertions in a page-object pattern? Should assertions be written in
the page object test methods or in the higher level test methods that
will use the PageObject classes?
My personal choice is to use assertions in Test methods, since it is where we are doing the actual testing. Page objects contains scripts for navigating inside the web page.
How can I customize the failure reporting so that I can send a failure
result like "Expected element "button" with id "bnt12" but did not
find the element at step 3 of test-method" to testng's reporting
utility?
You can use extent report and testng listener class( in this class use onTestFailure method to customize your failure report).

Resources