It's often the case that you need to do some sort of cleanup after every test. For instance, cleaning the database.
QUESTION:
Is there a way to attach global tearDown and setUp functions when using the unittest library?
It'd be even better to be able to define around advice:
unittest.around((test){
//doing setup
test();
//doing cleanup
});
Of course, the bug needs to be fixed first :-)
Then you would do this as Justin says' using non-anonymous functions that you can upcall explicitly. It seemed to me that this was the best way of providing maximum flexibility without encumbering the unit test library with a lot of convoluted setup/teardown logic.
If you want to do test suite setup/teardown, you could do that with an initial/final "test" in the group:
group('test suite', () {
test('Set up suite', () { ... });
test('Test 1', () { ... });
...
test('Test n', () { ... });
test('Tear down suite', () { ... });
});
It's not ideal, but it is a solution.
It's worth pointing out that internally, groups are not actually represented as a hierarchy. All we are really doing is keeping a stack with the current setUp/tearDown functions so we can associate each test case with the appropriate ones, and concatenating the group names and test name to make the final name for the test case. We are not building a tree data structure, so we don't have a good way of doing upcalls implicitly (we could create closures on the fly that upcall one level, and use those as the actual setUp/tearDown functions, but that's a bit fugly).
You can do it manually, as Gram alludes to in the bug:
main() {
topSetup() {
// ...
}
setUp(topSetup);
group('group', () {
setUp(() {
topSetup();
// ...
});
test('test', () {
// ...
});
});
}
Related
Within the testing library framework, you can write a test like this where the expectation is implied, i.e. the test will fail as a result of the getByText method throwing if it can't find the given text:
it('sets some text', () => {
...
screen.getByText('someText');
});
Although this works, this is relying on the implementation detail of testing library. So, I'm curious to know if this is accepted, or whether an explicit expect should be in place, like
it('sets some text', () => {
...
expect(screen.getByText('someText')).toBeInTheDocument();
});
I wonder if there's a language sugar/SDK utility function in Dart that allows to protect a certain code from running more than once?
E.g.
void onUserLogin() {
...
runOnce(() {
handleInitialMessage();
});
...
}
I know I can add a global or class static boolean flag to check but it would be accessible in other functions of the same scope with a risk of accidental mixup in the future.
In C++ I could e.g. use a local static bool for this.
There is no built-in functionality to prevent code from running more than once. You need some kind of external state to know whether it actually did run.
You can't just remember whether the function itself has been seen before, because you use a function expression ("lambda") here, and every evaluation of that creates a new function object which is not even equal to other function objects created by the same expression.
So, you need something to represent the location of the call.
I guess you could hack up something using stack traces. I will not recommend that (very expensive for very little advantage).
So, I'd recommend something like:
class RunOnce {
bool _hasRun = false;
void call(void Function() function) {
if (_hasRun) return;
// Set after calling if you don't want a throw to count as a run.
_hasRun = true;
function();
}
}
...
static final _runOnce = RunOnce();
void onUserLogin() {
_runOnce(handleInitialMessage);
}
It's still just a static global that can be accidentally reused.
Is there a way to enforce the order of execution for a broadcast stream with multiple listeners where order of execution matters?
StreamSubscription<T> listen(void onData(T event)?,
{Function? onError, void onDone()?, bool? cancelOnError});
The abstract definition doesn't seem to support it. I was looking for perhaps something like a 'priority' parameter to specify the order of operation.
For example, right now I have a UserController that notify its listeners to do something when the user changes. However, some of the listeners need to be prioritised, but they need to be in their own separate class. Example code:
class UserController{
Stream user;
}
class IndependentControllerA {
//...
userController.user.listen((){
// This needs to be carried out first before everything else
}
//...
}
class IndependentControllerB {
userController.user.listen((){
// This needs to be carried out before A
}
}
What I have thought to overcome this is for UserController to instead register a list of its own Future callbacks that can be awaited in order. See example:
class UserController {
List<Future Function()> callbacks;
void changeUser() async {
callbacks.forEach((callback) => await callback());
}
}
class IndependentControllerA {
//...
userController.callbacks.add(() => print('Do first thing'));
//...
}
class IndependentControllerB {
//...
userController.callbacks.add(() => print('Do second thing'));
//...
}
However, I feel that this is not very elegant, if there is a better innate way to do this already with stream. Is there?
The order that listeners are notified in is definitely not something Dart promises. In practice, it's likely to be ordered in some way depending on the order the listeners were added, but it's not a guarantee, and it might change at any time. (Not really, there's definitely badly written code which depends on the ordering and will break if the ordering changes, but that just means there'll have to be a good reason for the change, not that it can't happen).
I'd write my own "prioritizer" if I had such a specific need. Something like what you have started here. Knowing the specific requirements you have might make it much simpler than making a completely general solution.
I have some translation components that I would like to use only in the development environment. The idea is that the component does not get compiled when the project builds.
How can I achieve that in AngularDart 5?
Depending on how you'd like your component to be loaded/not loaded, there are different strategies you can take. My preferred one usually is to have two entry-points for your application, i.e. web/main.dart, and web/main.dev.dart, and have the latter be the only one that imports/uses/loads the component in question.
For example, you could have the following definition in lib/translation.dart:
void Function() loadTranslationComponent = () {};
And in web/main.dev.dart:
import 'package:name/translation.dart';
void main() {
loadTranslationComponent = () {
// Code to initialize and use only in development mode.
};
}
I'm writing a C++/CX component to be consumed by Window's store Apps. I'm looking for a way to accomplish what Task.Delay(1000) does in C#.
Old Question, but still unanswered.
You can use
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
This will need C++11, which shouldn't be a problem when using C++/CX.
After one year of using C++/CX, I have a general and reasonably correct answer to this question.
This link (from the Visual C++ Parallel Patterns Library documentation) includes a snippet for a function called complete_after(). That function creates a task that will complete after the specified number of milliseconds. You can then define a continuation task that will execute afterwards:
void MyFunction()
{
// ... Do a first thing ...
concurrency::create_task(complete_after(1000), concurrency::task_continuation_context::use_current)
.then([]() {
// Do the next thing, on the same thread.
});
}
Or better yet, if you use Visual C++'s coroutines capabilities simply type:
concurrency::task<void> MyFunctionAsync()
{
// ... Do a first thing ...
co_await complete_after(1000);
// Do the next thing.
// Warning: if not on the UI thread (e.g., on a threadpool thread), this may resume on a different thread.
}
You could create a concurrency::task, wait for 1000 time units and then call the ".then" method for the task. This will ensure that there is at least a wait of 1000 time units between the time you created the task and between the time it gets executed.
I'm not going to claim to be a wizard - I'm still fairly new to UWP and C++/CX., but what I'm using is the following:
public ref class MyClass sealed {
public:
MyClass()
{
m_timer = ref new Windows::UI::Xaml::DispatcherTimer;
m_timer->Tick += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &MyClass::PostDelay);
}
void StartDelay()
{
m_timer->Interval.Duration = 200 * 10000;// 200ms expressed in 100s of nanoseconds
m_timer->Start();
}
void PostDelay(Platform::Object^ sender, Platform::Object ^args)
{
m_timer->Stop();
// Do some stuff after the delay
}
private:
Windows::UI::Xaml::DispatcherTimer ^m_timer;
}
The main advantage over other approaches is that:
it's non-blocking
You're guaranteed to be called back on the XAML UI thread