light inject - unit testing - unit-testing

I have an c# interface with multiple implementations & each implementation is taking various dependencies object in its constructor.
In order to achieve DI using LightInjector on web api project, Im registering a 'Func' like below & its working as expected but can't able to unit test it.
Any way I can write the below code in unit testable way?
container.RegisterInstance<Func<IHandler, HandlerType, IHandler>>
((handler, type) =>
{
IHandler context = null;
switch (type)
{
case HandlerType.Type0:
context = new Type0(orderHandler, container.GetInstance<IUtilityLogic>());
break;
case HandlerType.Type1:
context = new Type1(orderHandler, container.GetInstance<IUtilityLogic>(), container.GetInstance<IShipmentLogic>());
break;
case HandlerType.Type2:
context = new Type2(orderHandler);
break;
case HandlerType.Type3:
context = new Type3(orderHandler, container.GetInstance<IUtilityLogic>());
break;
case HandlerType.Type4:
context = new Type4(orderHandler, container.GetInstance<IUtilityLogic>(), container.GetInstance<IShipmentLogic>(), container.GetInstance<Func<string, string, ICache>>());
break;
default:
context = null;
break;
}
return context;
});

Related

Rider for UE: build don't have any effect

Not sure if it's a software issue or my incredible programming skills.
I'm using UE4.27 and Rider for UE 2021.2.1 for C++ project. Recently I got some strange bug or something else: some changes in the code do not affect the program in any way. For example, there are old logs (Unable to get Owner Actor, AttackMontageN) that still work fine and new logs (NewLog) that didn't work, but there are no errors while building, crashes or anything like this:
void UMeleeAttackAbility::CommitExecute(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo,
const FGameplayAbilityActivationInfo ActivationInfo)
{
Super::CommitExecute(Handle, ActorInfo, ActivationInfo);
const auto Owner = ActorInfo->OwnerActor.Get();
if (!Owner)
{
UE_LOG(LogPRAbilitySystemBase, Error, TEXT("Unable to get Owner Actor"))
K2_EndAbility();
}
UE_LOG(LogPRAbilitySystemBase, Warning, TEXT("NewLog"));
const int MontageIndex = rand() % 3;
switch(MontageIndex)
{
case 0:
UE_LOG(LogPRAbilitySystemBase, Warning, TEXT("AttackMontage1"));
AttackMontage = AttackMontage1;
break;
case 1:
UE_LOG(LogPRAbilitySystemBase, Warning, TEXT("AttackMontage2"));
AttackMontage = AttackMontage2;
break;
case 2:
UE_LOG(LogPRAbilitySystemBase, Warning, TEXT("AttackMontage3"));
AttackMontage = AttackMontage3;
break;
default:
break;
}
UE_LOG(LogPRAbilitySystemBase, Warning, TEXT("NewLog"));
//...
}
I reverted to one very old commit where this code is completely different, but the results in the logs and character behavior are still the same. Also I'm tried to rebuild current project (in Advanced Build Actions) and do some other obvious things such restarting UE4/Rider, etc. Is it Rider problem or it can be something else?

Obtaining wi-fi connection status from Connection Manager

I have some code which successfully iterates over a list of wi-fi networks, and provides feedback about available networks. The essential calls shown here...
WlanOpenHandle(WLAN_API_VERSION, NULL, &dwVersion, &hSession);
PWLAN_INTERFACE_INFO_LIST pInterfaceInfoList = NULL;
WlanEnumInterfaces(hSession, NULL, &pInterfaceInfoList);
for(int i ...)
{
PWLAN_AVAILABLE_NETWORK_LIST pAvailableNetworkList = NULL;
WlanGetAvailableNetworkList(hSession, &interfaceGUID,
WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES |
WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES,
NULL, &pAvailableNetworkList);
for(int j ...)
{
WLAN_AVAILABLE_NETWORK network = pAvailableNetworkList->Network[j];
:
}
}
This all works fine, and inside the inner loop I'm able to access all of the attributes that I need, such as signal strength, security flags, etc via the network data structure.
One thing that I am not able to obtain is information regarding connection status, such as AUTHENTICATING or AUTHENTICATION_FAILED, etc, so I have tried to introduce another call inside the loop as follows...
CM_CONNECTION_DETAILS connectionDetails;
memset(&connectionDetails, 0, sizeof(CM_CONNECTION_DETAILS));
connectionDetails.Version = CM_CURRENT_VERSION;
const char* ccp = reinterpret_cast<const char*>(network.dot11Ssid.ucSSID);
mbstowcs(connectionDetails.szName, &ccp[0], network.dot11Ssid.uSSIDLength);
DWORD dwCount = sizeof(CM_CONNECTION_DETAILS);
CM_RESULT cmr = CmGetConnectionDetailsByName(connectionDetails.szName,
&connectionDetails, &dwCount);
if (cmr == CMRE_SUCCESS)
{
:
}
Upon calling the CmGetConnectionDetailsByName() function, the details inside the CM_CONNECTION_DETAILS structure look correct (name and version), but the function returns with CMRE_INVALID_CONNECTION and the structure is not populated.
I haven't been able to find any examples of this call being successful (only a couple of references to the call returning the same CMRE_INVALID_CONNECTION code).
Does anyone have any experience of using the call successfully, or alternatively suggest a better way to find out the connection status of a network (ie if AUTHENTICATION is in progress or if AUTHENTICATION failed, etc)?
[I'm using Visual Studio 2013 C++ (native Windows app, not MFC), the target is 32-bit and Unicode, running on Windows Compact 2013]
The function below doesn't quite give me the fine control that I was looking for, but it does at least give me the opportunity to find out the state a particular interface. This means that I can find out if the interface is currently in the process or authenticating, and depending whether the final state is connected or disconnected, I can find out if authentication was successful or not.
WLAN_INTERFACE_STATE getNetworkState(HANDLE hSession, GUID* pGUID, std::wstring& wsState, bool bReportState=true)
{
WLAN_INTERFACE_STATE result = wlan_interface_state_not_ready;
DWORD dwDataSize;
void* pData;
DWORD dwErrorCode = WlanQueryInterface(hSession, pGUID, wlan_intf_opcode_interface_state, NULL, &dwDataSize, &pData, NULL);
if (dwErrorCode == ERROR_SUCCESS && pData != NULL)
{
WLAN_INTERFACE_STATE* pState = reinterpret_cast<WLAN_INTERFACE_STATE*>(pData);
if (pState != NULL)
{
switch (*pState)
{
case wlan_interface_state_not_ready: wsState = L"NOT_READY"; break;
case wlan_interface_state_connected: wsState = L"CONNECTED"; break;
case wlan_interface_state_ad_hoc_network_formed: wsState = L"AD_HOC_NETWORK_FORMED"; break;
case wlan_interface_state_disconnecting: wsState = L"DISCONNECTING"; break;
case wlan_interface_state_disconnected: wsState = L"DISCONNECTED"; break;
case wlan_interface_state_associating: wsState = L"ASSOCIATING"; break;
case wlan_interface_state_discovering: wsState = L"DISCOVERING"; break;
case wlan_interface_state_authenticating: wsState = L"AUTHENTICATING"; break;
}
result = *pState;
}
WlanFreeMemory(pData);
}
return result;
}
A limitation of this check, is that it doesn't readily support multiple connections on the same interface, This query doesn't allow us to query to which of the connections the status refers.
If I arrive at a better solution, I will report it here.

Salesforce Apex unit testing error

I am trying to create a Salesforce unit test for a new trigger I created.
trigger SOSCreateCaseCustom on SOSSession (before insert) {
List<Event> aplist = new List<Event>();
List<SOSSession> sosSess = Trigger.new;
for (SOSSession s : sosSess) {
try {
Case caseToAdd = new Case();
caseToAdd.Subject = 'SOS Video Chat';
if (s.ContactId != null) {
caseToAdd.ContactId = s.ContactId;
} else {
List<Contact> contactInfo = [SELECT Id from Contact WHERE Email = :s.AppVersion];
if (!contactInfo.isEmpty()) {
caseToAdd.ContactId = contactInfo[0].Id;
s.ContactId = contactInfo[0].Id;
}
}
insert caseToAdd; s.CaseId = caseToAdd.Id;
}catch(Exception e){}
}
}
Here is my unit test:
#isTest
private class SOSCreateCaseCustomTest {
static testMethod void validateSOSCreateCase() {
String caseSubject = 'SOS Video Chat';
// set up case to add
SOSSession s = new SOSSession();
insert s;
Case caseToAdd = new Case(Subject='SOS Video Chat');
caseToAdd.ContactId = s.ContactId;
insert caseToAdd;
Case ca = [SELECT Subject, ContactId from Case where Subject =: caseSubject];
// Test that escaltion trigger correctly escalate the question to a case
System.assertEquals(s.ContactId, ca.ContactId);
}
}
I keep getting this error.
System.QueryException: List has more than 1 row for assignment to SObject
I am new to Apex and I have no idea how to fix this. Any Salesforce and Apex experts out there who can help? Thanks!
I think this one:
Case ca = [SELECT Subject, ContactId from Case where Subject =: caseSubject];
Because the casSubject may query more then one Case.... You should use List
The following line is causing issue :
Case ca = [SELECT Subject, ContactId from Case where Subject =: caseSubject];
It is returning two cases, the one you inserted in test data and other that is inserted by trigger. So it is having two records for Subject 'SOS Video Chat';
If you change the Subject from 'SOS Video Chat' to any other String it will run successfully.

Remove 'component' word from urls for my custom non mvc component in joomla

I wrote a custom non-mvc component (because i don't know how to make mvc component and now it's grown is size so changing it will take more time which is not possible for me) 'com_group' for my client.
Everything is fine but when it comes to sef urls it gives me urls like mysite/component/group/home and in non sef urls like mysite/index.php?option=com_group&view=home but client wants to remove component word from urls.
I also made a router for my component which remove every parameter correctly but it does not remove component. I also made a menu item for it but it didn't helped me.
Here is my router.php
<?php //error_reporting(E_ALL);
defined ( '_JEXEC' ) or die ();
jimport('joomla.error.profiler');
function GroupBuildRoute(&$query){
$segments = array();
//$query['Itemid'] = 201;
if( isset($query['view']) )
{
$segments[] = $query['view'];
unset( $query['view'] );
};
if( isset($query['pin']) )
{
$segments[] = $query['pin'];
unset( $query['pin'] );
};
return $segments;
}
function GroupParseRoute($segments){
$vars = array();
$app =& JFactory::getApplication();
$menu =& $app->getMenu();
$item =& $menu->getActive();
$items = $menu->getItems('component', 'com_group');
if (!isset($query['Itemid']))
$query['Itemid'] = 180;//$items->id;
// Count segments
$count = count( $segments );
//Handle View and Identifier
switch( $segments['0'] ){
case 'group_page':
$vars['view'] = 'group-pages';
break;
case 'group':
$vars['view'] = 'home';
break;
case 'folow':
$vars['view'] = 'follow';
break;
case 'start':
$vars['view'] = 'start-group';
break;
case 'group_eventplan':
$vars['view'] = 'group-event-plan';
break;
case 'group_member':
$vars['view'] = 'group-members';
break;
case 'manage_subscription':
$vars['view'] = 'manage-subscription';
break;
case 'group_msg':
$vars['view'] = 'group-message';
break;
case 'group_invite':
$vars['view'] = 'invite-friends';
break;
case 'other_group':
$vars['view'] = 'other-groups';
break;
case 'groupinfo':
$vars['view'] = 'group-info';
break;
case 'home':
$vars['view'] = 'group-home';
break;
}
if (!isset($item)) {
$vars['view'] = $segments[0];
$vars['pin'] = $segments[1];
return $vars;
}
if($count==2){
$vars['view'] = $vars['view'];
$vars['pin'] = $segments[1];
return $vars;
}
return $vars;
}
I also want to replace group_msg to group-message also so that new urls should be component/group/group-message/ not component/group/group_msg
I tried Remove component part from sef url, menu item not completely but didn't helped me.
Finally i managed to solve the question by myself. I am mentioning steps taken to help others. (Please write me if you want source code to use it with your project)
Step 1: add a menu item (Joomla Administrator -> Menus ->Menu Manager->Add new Item)
Step 2: The newly added menu item will be provided an id, add this id to all urls of your component like this.
index.php?option=com_your_component_name&Itemid=newly_generated_id
that's it.
The first option I would try is sh404SEF
Good luck!
EDIT
If SEF extensions are not an option for you, perhaps using .htaccess and redirect, something like the following :
RewriteEngine On
Redirect /component/group/home /something-else

Doctrine Query Builder not registering parameter?

I have the following code which is throwing the exception Invalid parameter number: number of bound variables does not match number of tokens. Yet when I print the registered parameters, my parameter is showing up.
public function getUnitPriceFor($entityType,$entityID,$qty,$configuration_id)
{
$this->qb = $this->getEntityManager()->createQueryBuilder();
$this->qb ->select($this->_entities[$entityType]['select'])
// for Base this would be ->select(array('t','c','w','g'))
// for the other cases below, like website, it's array('t','w')
->from('AcmeBundle:PriceTier', 't');
switch($entityType) :
case 'base' :
$this->qb ->leftJoin('t.customers','c')
->leftJoin('t.customergroups','g')
->leftJoin('t.websites','w');
break;
case 'website' :
$this->qb ->join('t.websites','w','WITH','w.id = '.$entityID);
break;
case 'custgrp' :
$this->qb ->join('t.customergroups','g','WITH','g.id = '.$entityID);
break;
case 'cust' :
$this->qb ->join('t.customers','t','WITH','t.id = '.$entityID);
break;
endswitch;
$this->qb ->where('t.printconfiguration = :configuration_id');
$this->qb ->setParameter('configuration_id', $configuration_id);
print_r( $this->qb->getParameters() );
$dql = $this->qb->getDQL();
echo"<pre>";
print_r($this->getEntityManager()->createQuery($dql)->getArrayResult());
echo"</pre>";
}
Printing $this->qb->getParameters(); shows me Array ( [configuration_id] => 1 ), and removing my where and set parameter clauses prevents the exception from occurring. Finally, (and get this), if I remove my where clause but keep the parameter set, no exception occurs. I'm rather confused.
Apparently $dql = $this->qb->getDQL(); will not pass parameters.
I needed to change
$dql = $this->qb->getDQL();
echo"<pre>";
print_r($this->getEntityManager()->createQuery($dql)->getArrayResult());
echo"</pre>";
to
$query = $this->qb->getQuery();
echo"<pre>";
print_r($query->getArrayResult());
echo"</pre>";