How do I execute something on Test Suite Setup/Teardown? - karate

is there such thing as a Test Suite Setup/Teardown in Karate API?
Basically, I want to do something before everything starts and after everything is finished.

If you are using Java / JUnit as the entry point this is quite simple, just add lines of code before / after.
Also refer this answer: https://stackoverflow.com/a/59080128/143475 - the ExecutionHook (which still does require you to write Java code) has beforeAll() and afterAll() callbacks.
In practice it is probably simplest to use a callSingle() in your karate-config.js and do a pre-cleanup.

Fixed via below code.
<...truncated imports...>
#KarateOptions()
public class TestRunner {
#Test
public void testParallel() {
Results results = Runner.path("classpath:THISCLASS").hook(new ExecHook()).parallel(1);
generateReport(results.getReportDir());
assertTrue(results.getErrorMessages(), results.getFailCount() == 0);
}
}
class ExecHook implements ExecutionHook {
#Override
public void afterAll(Results results) {
System.out.println("DO SOMETHING HERE");
}
#Override
public boolean beforeScenario(Scenario scenario, ScenarioContext context) {
return true;
}
#Override
public void afterScenario(ScenarioResult result, ScenarioContext context) {
}
#Override
public boolean beforeFeature(Feature feature, ExecutionContext context) {
return true;
}
#Override
public void afterFeature(FeatureResult result, ExecutionContext context) {
}
#Override
public void beforeAll(Results results) {
}
#Override
public boolean beforeStep(Step step, ScenarioContext context) {
return true;
}
#Override
public void afterStep(StepResult result, ScenarioContext context) {
}
#Override
public String getPerfEventName(HttpRequestBuilder req, ScenarioContext context) {
return null;
}
#Override
public void reportPerfEvent(PerfEvent event) {
}
}
Just one question, is there a way to to take off the #Overrides for the methods I'm not using?

Related

Access Activity from ViewManager in React Native

How are you? I have a some issues in my project.
Here is my code.
public class ViewManager extends ViewGroupManager<FrameLayout> {
public static final String REACT_CLASS = "RNNativeFlip";
public final int COMMAND_CREATE = 1;
private ReactApplicationContext context;
public ViewManager(ReactApplicationContext context) {
this.context = context;
}
#NonNull
#Override
public String getName() {
return REACT_CLASS;
}
#Override
protected FrameLayout createViewInstance(ThemedReactContext reactContext) {
return new FrameLayout(reactContext);
}
#Nullable
#Override
public Map<String, Integer> getCommandsMap() {
return MapBuilder.of("create", COMMAND_CREATE);
}
#Override
public void receiveCommand(
#NonNull FrameLayout root,
int commandId,
#Nullable ReadableArray args
) {
super.receiveCommand(root, commandId, args);
int reactNativeViewId = args.getInt(0);
int commandIdInt = commandId;
switch (commandIdInt) {
case COMMAND_CREATE:
createFragment(root, reactNativeViewId);
break;
default: {}
}
}
public void createFragment(FrameLayout root, int reactNativeViewId) {
final MainFragment myFragment = new MainFragment();
FragmentActivity activity;
activity = (FragmentActivity) this.context.getCurrentActivity();
activity.getSupportFragmentManager()
.beginTransaction()
.replace(reactNativeViewId, myFragment, String.valueOf(reactNativeViewId))
.commit();
}
}
No longer possible to access Activity from getCurrentActivity()
I know one method to use ReactContextBaseJavaModule but I don't know how to use this in ViewManger.
Please help me. Thank you

How to add a simple tab in Intellij Idea plugin

I am creating a simple class diagram plugin for Intellij Idea. I'm struggling now with creating a simple tab in IDE. This tab I will fill up with a prepared JPanel and nothing else.
I have already done the same in NetBeans and I would like to find something with similar behavior as TopComponent in NetBeans provides, but anything working would be cool.
So here is the answer:
create implementation of com.intellij.openapi.fileEditor.FileEditor. This is your actual tab
create implementation of com.intellij.openapi.fileEditor.FileEditorProvider
accept() defines type of files which your editor opens
create() should returns the proper instance of your editor
register your FileEditoProvider in plugin.xml
Editor:
public class YourEditor implements FileEditor {
private VirtualFile file;
public YourEditor(VirtualFile file) {
this.file = file;
}
#Override
public #NotNull JComponent getComponent() {
JPanel tabContent = new JPanel();
tabContent.add(new JButton("foo"));
return tabContent;
}
#Override
public #Nullable JComponent getPreferredFocusedComponent() {
return null;
}
#Override
public #Nls(capitalization = Nls.Capitalization.Title)
#NotNull String getName() {
return "name";
}
#Override
public void setState(#NotNull FileEditorState fileEditorState) {
}
#Override
public boolean isModified() {
return false;
}
#Override
public boolean isValid() {
return true;
}
#Override
public void addPropertyChangeListener(#NotNull PropertyChangeListener propertyChangeListener) {
}
#Override
public void removePropertyChangeListener(#NotNull PropertyChangeListener propertyChangeListener) {
}
#Override
public #Nullable FileEditorLocation getCurrentLocation() {
return null;
}
#Override
public void dispose() {
Disposer.dispose(this);
}
#Override
public <T> #Nullable T getUserData(#NotNull Key<T> key) {
return null;
}
#Override
public <T> void putUserData(#NotNull Key<T> key, #Nullable T t) {
}
#Override
public #Nullable VirtualFile getFile() {
return this.file;
}
}
Provider:
public class YourEditorProvider implements FileEditorProvider, DumbAware {
private static String EDITOR_TYPE_ID = "DiagramView";
#Override
public boolean accept(#NotNull Project project, #NotNull VirtualFile virtualFile) {
return true; //will accept all kind of files, must be specified
}
#Override
public #NotNull
FileEditor createEditor(#NotNull Project project, #NotNull VirtualFile virtualFile) {
return new YourEditor(virtualFile);
}
#Override
public #NotNull
#NonNls
String getEditorTypeId() {
return EDITOR_TYPE_ID;
}
#Override
public #NotNull
FileEditorPolicy getPolicy() {
return FileEditorPolicy.HIDE_DEFAULT_EDITOR;
}
}
and finally put FileEditorProvider extension in pluxin.xml:
<extensions defaultExtensionNs="com.intellij">
<fileEditorProvider implementation="classDiagramPainter.DiagramViewProvider"/>
</extensions>

JUnit5 afterAll callback fires at the end of each test class and not after all tests

I have 15 JUnit5 classes with tests. When I run them all from maven, the afterAll() is executed 15 times which causes 15 notifications to a Slack Webhook. Is there anything else I need to only send one notification?
public class TestResultsExtensionForJUnit5 implements TestWatcher, AfterAllCallback {
#Override
public void afterAll(ExtensionContext extensionContext) throws Exception {
sendResultToWebHook();
}
#Override
public void testDisabled(ExtensionContext context, Optional<String> reason) {
totalTestDisabled = totalTestDisabled + 1;
}
#Override
public void testSuccessful(ExtensionContext context) {
totalTestPassed = totalTestPassed + 1;
}
#Override
public void testAborted(ExtensionContext context, Throwable cause) {
totalTestAborted = totalTestAborted + 1;
}
#Override
public void testFailed(ExtensionContext context, Throwable cause) {
totalTestFailed = totalTestFailed + 1;
}
}
#ExtendWith(TestResultsExtensionForJUnit5.class)
public class Random1Test {}
The best way is to implement and install a TestExecutionListener from the JUnit Platform, as it is described in the User Guide at https://junit.org/junit5/docs/current/user-guide/#launcher-api-listeners-custom -- override the default testPlanExecutionFinished​(TestPlan testPlan) method with your notifying call. Here, all tests from all engines are finished.

How to manage the life cycle in react native

I know when we need a nativeUI component we need override function
getName()and
createViewInstance(ThemedReactContext context) But when I use a dependence about map. The API need me use the component like this
#Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),
mMapView.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),
mMapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),
mMapView.onPause();
}
}
I override the function getetName()and
createViewInstance(ThemedReactContext context) like this
#Override
public String getName() {
return REACT_CLASS;
}
#Override
public MapView createViewInstance(ThemedReactContext context) {
final ThemedReactContext mapContext = context;
bdMapViewInstance = new MapView(context);
bdMapViewInstance.getMap().setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
ShopResponseInfo shopResponseInfo = (ShopResponseInfo) marker.getExtraInfo().getSerializable(INDENTIFY);
if(shopResponseInfo != null){
String id = shopResponseInfo.getShop_id() + "";
String shop_name = shopResponseInfo.getShop_name() + "";
onReceiveNativeEvent(mapContext,bdMapViewInstance,id,shop_name);
}
return true;
}
});
return bdMapViewInstance;
}
Finally There are some performance question in my app. I don't know whether it is affect on my app's performance. And I don't know how to meet the official suggestion. I don't know how to control the life cycle of nativeUI component for android. Very Thanks.
You can listen to activity life cycle like this in your createViewInstance. You probably want to keep track of listeners and remove them appropriately based on you keep track of your instances.
LifecycleEventListener lifecycleEventListener = new LifecycleEventListener() {
#Override
public void onHostResume() {
}
#Override
public void onHostPause() {
}
#Override
public void onHostDestroy() {
}
};
getReactApplicationContext().addLifecycleEventListener(lifecycleEventListener);
An example of TestModule as explained in the docs of RN. PS Don't forget to use implements LifecycleEventListener
package com.testpackage;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.LifecycleEventListener;
import java.util.Map;
import java.util.HashMap;
public class TestModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
public TestModule(ReactApplicationContext reactContext) {
super(reactContext);
reactContext.addLifecycleEventListener(this);
}
#Override
public void onHostResume() {
}
#Override
public void onHostPause() {
}
#Override
public void onHostDestroy() {
}
}

Nhibernate Isession with ninject

I am building an mvc4 n layer application using the following frameworks
1.nhibernate
2.ninject
3.mvc4/Console(For testing)
The layers are(All are class library projects)
1.Presentation(Calling BLL layer)
2.BLL(Calling my DAO layer)
3.Domain(POCOS)
4.Nhibernate(Implementation of DAO)
5.Core
BLL Layer Coding
public interface IUserService
{
IList<User> GetAllActiveUsers();
User GetUserDetailsByUsername(string usernameOrEmail);
}
public class UserService :IUserService
{
private readonly IUserRepository userRepository;
public UserService(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
public IList<User> GetAllActiveUsers()
{
var activeUserList = from user in userRepository.All()
where user.ACTIVE_STATUS == true
select user;
return activeUserList.ToList<User>();
}
public User GetUserDetailsByUsername(string usernameOrEmail)
{
var registerUser = from user in userRepository.All()
where user.USER_NAME == usernameOrEmail
select user;
return (User)registerUser;
}
}
DAO layer Code
public interface IRepository<TKey, TEntity> where TEntity : class
{
IQueryable<TEntity> All();
TEntity FindBy(Expression<Func<TEntity, bool>> expression);
IQueryable<TEntity> FilterBy(Expression<Func<TEntity, bool>> expression);
TEntity FindBy(TKey id);
bool Add(TEntity entity);
bool Add(IEnumerable<TEntity> items);
bool Update(TEntity entity);
bool Delete(TEntity entity);
bool Delete(IEnumerable<TEntity> entities);
}
public interface IUowDAO:IDisposable
{
void Commit();
void Rollback();
}
public interface IUserRepository:IRepository<long,User>
{
}
DAO.Nhibernate Layer
public class IURMSNhibernateRepository<TKey, T> : IRepository<TKey, T> where T : class
{
private readonly ISession _session;
public IURMSNhibernateRepository(ISession session)
{
_session = session;
}
public bool Add(T entity)
{
_session.Save(entity);
return true;
}
public bool Add(IEnumerable<T> items)
{
foreach (T item in items)
{
_session.Save(item);
}
return true;
}
public bool Update(T entity)
{
_session.SaveOrUpdate(entity);
return true;
}
public bool Delete(T entity)
{
_session.Delete(entity);
return true;
}
public bool Delete(IEnumerable<T> entities)
{
foreach (T entity in entities)
{
_session.Delete(entity);
}
return true;
}
public System.Linq.IQueryable<T> All()
{
return _session.Query<T>();
}
public T FindBy(System.Linq.Expressions.Expression<Func<T, bool>> expression)
{
return FilterBy(expression).SingleOrDefault();
}
public System.Linq.IQueryable<T> FilterBy(System.Linq.Expressions.Expression<Func<T, bool>> expression)
{
return All().Where(expression).AsQueryable();
}
public T FindBy(TKey id)
{
return _session.Get<T>(id);
}
}
public class IURMSUnitOfWork:IUowDAO
{
private readonly ISessionFactory _sessionFactory;
private readonly ITransaction _transaction;
public ISession Session { get; private set; }
public IURMSUnitOfWork(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
Session = _sessionFactory.OpenSession();
Session.FlushMode = FlushMode.Auto;
_transaction = Session.BeginTransaction(IsolationLevel.ReadCommitted);
}
public void Commit()
{
if (!_transaction.IsActive)
{
throw new InvalidOperationException("Oops! We don't have an active transaction");
}
_transaction.Commit();
}
public void Rollback()
{
if (_transaction.IsActive)
{
_transaction.Rollback();
}
}
public void Dispose()
{
if (Session.IsOpen)
{
Session.Close();
}
}
}
public class UserRepository:IURMSNhibernateRepository<long,User>,IUserRepository
{
public UserRepository(ISession session)
: base(session)
{
}
}
CORE Layer
public class BuisnessLogicModule:NinjectModule
{
public override void Load()
{
Bind<IUserService>().To<UserService>();
}
}
public class DataAccessLogicModule:NinjectModule
{
public override void Load()
{
Bind<IUowDAO>().To<IURMSUnitOfWork>().InTransientScope();
Bind(typeof(IRepository<,>)).To(typeof(IURMSNhibernateRepository<,>));
Bind<IUserRepository>().To<UserRepository>();
}
}
Console layerCoding
public interface IConsole
{
IList<User> GetAllUsers();
}
public class ConsoleUser:IConsole
{
private readonly IUserService _userService;
public ConsoleUser(IUserService UserService)
{
this._userService = UserService;
}
public IList<IURMSPOC.DOMAIN.User> GetAllUsers()
{
var user = _userService.GetAllActiveUsers();
return user;
}
}
public class TopModule:NinjectModule
{
public override void Load()
{
Bind<IConsole>().To<ConsoleUser>();
}
}
public class Program
{
static void Main(string[] args)
{
IKernel kernel = new StandardKernel(new TopModule());
var modules = new List<INinjectModule>
{
new IURMSPOC.CORE.Dependency.BuisnessLogicModule(),
new IURMSPOC.CORE.Dependency.DataAccessLogicModule(),
};
kernel.Load(modules);
var topClass = kernel.Get<IConsole>();
var message = topClass.GetAllUsers();
System.Console.WriteLine(message);
System.Console.WriteLine("Press enter to continue...");
System.Console.ReadLine();
}
}
But when i am running the application the error shows Error activating ISession
No matching bindings are available, and the type is not self-bindable.
I am new to ninject and nhibernate .Please give me the solution .I understand the problem but can not find any solution.
That's not an issue of Nhibernate, I guess the error comes from the ctor of
public UserRepository(ISession session)
: base(session)
{
}
Where you require an ISession.
You construct the session in IURMSUnitOfWork so there is no way for the UserRepository to determine the session or for the injection to figure out where ISession is coming from...
Instead I'd suggest to refactor your code and inject your unit of work instance to where it is needed, or refactor the repository to care about unit of work.
Easiest would be to extend IUowDAO with something like GetSession()
and change
public UserRepository(IUowDAO dao)
: base(dao.GetSession())
{
}
or something like that...
Your implementation is a little bit strange. Your data access object has the signature of a transaction etc... maybe read this article for a basic unit of work implementation with nhibernate.
What your are missing is basically the session factory.