I try to share some data between processes in my backend. How to protect them in async application without mutexes? I try to find something in documentation, but there is nothing in search on 'mutex' request.
I expect something like this:
http_listener listener(on_host);
listener.support([](http_request request) {
GLOBAL_VAR.Async_Mutex.lock(); {
GLOBAL_VAR.do_something();
} GLOBAL_VAR.Async_Mutex.unlock();
return request.reply(200);
});
listener
.open()
.wait();
Related
I'm trying to write a test for a method that makes a call to an API using Dio. The Dio response has been mocked using http_mock_adapter. My problem is that I need to wait for the API call to finish before continuing with the test, and I can't simply use await since the method I'm testing isn't asynchronous. Is there a way to wait for a future that wasn't called from the test?
Below is an example of what I'm talking about:
String apiResult = 'foo';
void methodToTest(){
apiCall().then((value) => apiResult = value);
}
test('methodToTest works', () {
expect(apiResult, equals('foo'));
methodToTest();
// I need to wait for apiCall to finish here.
expect(apiResult, equals('bar'));
});
Previously, I have been able to use Future.delayed(Duration.zero) when I have had situations like this, but it has always seemed like a workaround, and now it doesn't work.
the method I'm testing isn't asynchronous
Congratulations, your tests found a bug.
this is your method after fixing the bug:
Future<void> methodToTest() async {
apiResult = await apiCall();
}
I have a class Communicator that tests whether it can connect the test server. Here is how I call it:
class CommunicatorTest
{
public:
CommunicatorTest() {}
bool doTest()
{
bool _success;
Parameters params;
Communicator communicator;
communicator.connect(params, [this, &_success](bool success)
{
statusCode = errorCode;
m_condition.notify_one();
});
std::unique_lock<std::mutex> uGuard(m_mutex);
m_condition.wait(uGuard);
return _success;
}
private:
std::mutex m_mutex;
std::condition_variable m_condition;
};
bool communicatorTest()
{
CommunicatorTest test;
bool success = test.doTest();
return success;
}
TEST(CommunicatorTest, test_eq)
{
EXPECT_EQ(communicatorTest(), true);
}
I tried to use condition and mutex to make this code synchronous but it fails, the logs say only that test was running and immediately finishes.
Is there a way to test success variable from the callback using google tests?
Thanks in advance.
In those cases the best solution is to create a mock that emulates the behavior of the server. You should not rely (unless extremely necessary) in external states when running your tests.
The tests may fail because the server is not connected, there is no internet connection or whatever condition.
You can use something like Google Mock, now part of Google Test suite to emulate the behavior:
class MockServer : public Server {
public:
MOCK_METHOD2(DoConnect, bool());
....
};
Then do something like this:
TEST(ServerTest, CanConnect) {
MockServer s;
EXPECT_CALL(s, DoConnect())
..WillOnce(Return(true));
EXPECT_TRUE(server.isConnected());
}
You can simulate the error handling:
TEST(ServerTest, CannotConnect) {
MockServer s;
EXPECT_CALL(s, DoConnect())
..WillOnce(Return(false));
EXPECT_FALSE(server.isConnected());
// ... Check the rest of your variables or states that may be false and
// check that the error handler is working properly
}
As someone who writes asynchronous code, I have stumbled upon this problem many times - it seems most existing C/C++ test frameworks don't have real support for testing asynchronous code. What is mainly needed is a event loop where you can schedule things to be executed (to mock timed external events, etc), and a mechanism to register responses and optionally check the order in which they occur. So, instead of trying to somehow adopt an existing framework (which would result in probably greater effort), I created my own one. I have been using it to test a javascript-like promise class that I have developed, and it's done the job good for me. If you are interested, I have just published it on GitHub:
https://github.com/alxvasilev/async-test
I was trying to use loopback-component-storage. It's all working fine.
The one thing that I cannot figure out is how do I observe a file upload completion within loopback, when the following API is called:
http://localhost:3000/api/Epubs/{container}/upload | POST
I tried using afterRemote(".") & observe("access"). None of them seem to trigger.
You can use afterRemote on method 'upload'. In your case that will be
Epub.afterRemote( 'upload', function( ctx, modelInstance, next) {
...
next();
});
See remote hooks docs
I have a situation where as soon as app starts i have to call a web service to post unsaved data back to the server while i keep on accessing the app. I should be able to navigate to different views, perform UI tasks.
I can use Task
Task CallWebService()
{
return Task.Factory.StartNew(() => {
// make your service call.
});
}
CallWebService().ContinueWith(task => {
if(task.isFaulted)
throw new AggregateException(task.Exception.InnerException.Message);
// Runs when the task is finished
InvokeOnMainThread(() => {
// Hide your activity indicator here.
StopActivityIndicator();
});
});
I dont know where to call InvokeOnMainThread as user could be on any view. How do we handle that.
I would create the downloader as a static class with event handlers (or use dependency resolver). In your view controllers override ViewDidAppear and ViewDidDisappear where you will subscribe and unsubscribe to the events.
In your AppDelegate.cs, You can add your "Task" to the FinishedLaunching override and the OnActivated override, assuming you have a way to determine if there is any "unsaved" data, that needs to be sent to the server.
public override void OnActivated (UIApplication application)
{
}
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
}
I need to run some code after ember application got initialized. I don't want to invoke this code from App.ready to avoid tight coupling. It would be nice to have something like this:
App.on 'ready, -> console.log('do stuff')
But it won't work since Em.Application object is not subscribable and ready isn't really an event despite that docs said so
A simple way you can achieve this would be to extend your Application class with the Ember.Evented mixin:
App = Ember.Application.createWithMixins(Ember.Evented, {
ready: function() {
console.log('App ready');
this.trigger('appReady');
}
});
And you hook inside the ready event inside your app and trigger your custom event using this.trigger(...)
At this point you can use .on(...) to be notified when the event is triggered.
App.on('appReady', function() {
console.log('App already ready');
});
Example demo.
Hope it helps.
An other possibility may be to invoke your code from the resolve callback of the application.
App.then(function(app) {
console.log("App is resolved, so it's ready");
});
example stolen from #intuitivepixel ;) http://jsbin.com/AdOVala/66/edit
Edit/Note:
App.then() has been deprecated, see http://emberjs.com/deprecations/v1.x/#toc_code-then-code-on-ember-application:
As part of the Ember.DeferredMixin deprecation, using .then on an
Ember.Application instance itself has been deprecated.
You can use the ready hook or initializers to defer/advance readiness instead.