Skip to content

Commit

Permalink
Allow unit-testing try-catch(condition)
Browse files Browse the repository at this point in the history
Our CBot unit tests run in single-step mode.
Try-catch had a hack that prevented evaluation of catch conditions in single-step mode.

I have removed the hack to enable unit-testing, but that caused a different problem:
debugging code inside the body of try-catch became inconvenient because
the player had to manually step over every catch expression after every single instruction in try body.

I solved this by teaching CBotTry to step-over the catch conditions
  • Loading branch information
hexagonrecursion committed May 11, 2024
1 parent e00f99f commit 7266cb9
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
16 changes: 12 additions & 4 deletions CBot/src/CBot/CBotInstr/CBotTry.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,6 @@ bool CBotTry::Execute(CBotStack* &pj)
}

val = pile1->GetError();
if ( val == CBotNoErr && pile1->GetTimer() == 0 ) // mode step?
return false; // don't jump to the catch

pile1->IncState();
pile2->SetState(val); // stores the error number
Expand All @@ -124,8 +122,18 @@ bool CBotTry::Execute(CBotStack* &pj)
{
if ( --state <= 0 )
{
// ask to the catch block if it feels concerned
if ( !pc->TestCatch(pile2, val) ) return false; // suspend !
// Debugging QoL: automatically step over catch expressions
while ( true )
{
if ( pc->TestCatch(pile2, val) ) break;
if ( !pile2->IsOk() ) return false;
const int extraTicks = 100;
// Decrement and check the counter without changing pile0 state
if ( !pile0->SetState(1, -extraTicks) )
{
return false; // Prevent infinite loops and external calls from hanging the game
}
}
pile1->IncState();
}
if ( --state <= 0 )
Expand Down
21 changes: 21 additions & 0 deletions test/src/CBot/CBot_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3434,6 +3434,27 @@ TEST_F(CBotUT, TestTryCatch) {
"}\n",
CBotErrBadType1
);

ExecuteTest(
"extern void TestTryCatchCondition() {\n"
" int foo = 0;\n"
" try {\n"
" foo = 1;\n"
" for(int i = 0; i < 20; ++i); // Should give try an opportunity to check condition\n"
" foo = 2; // Should not get here\n"
" } catch(foo == 1);\n"
" ASSERT(foo == 1);\n"
"}\n"
);

ExecuteTest(
"extern void TestExcetionInCatchCondition() {\n"
" try {\n"
" for(int i = 0; i < 20; ++i); // Should give try an opportunity to check condition\n"
" } catch(1/0 == 0);\n"
"}\n",
CBotErrZeroDiv
);
}

TEST_F(CBotUT, TestFinally) {
Expand Down

0 comments on commit 7266cb9

Please sign in to comment.