diff --git a/app/build.gradle b/app/build.gradle index 024670a..15f9727 100755 --- a/app/build.gradle +++ b/app/build.gradle @@ -23,6 +23,13 @@ android { } } + testOptions { + unitTests { + // Robolectric tests read the app's resources (strings, puzzle CSVs) + includeAndroidResources = true + } + } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 @@ -31,4 +38,20 @@ android { dependencies { implementation libs.androidx.appcompat + + testImplementation libs.junit + testImplementation libs.robolectric +} + +tasks.withType(Test).configureEach { + // Robolectric sets up Android 16's file descriptors through JDK internals, + // which JDK 17+ only allows when they're exported/opened explicitly + jvmArgs '--add-exports=java.base/jdk.internal.access=ALL-UNNAMED', + '--add-opens=java.base/java.io=ALL-UNNAMED' + + // Print the full stack trace of failing tests in the build log (CI keeps nothing else) + testLogging { + events 'failed' + exceptionFormat = 'full' + } } diff --git a/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java b/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java index 9ebd739..de16a0c 100755 --- a/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java +++ b/app/src/main/java/atorch/shortestpaths/SolvePuzzle.java @@ -1,6 +1,7 @@ package atorch.shortestpaths; import android.content.ContentValues; +import java.util.ArrayList; import java.util.Arrays; import java.util.Random; @@ -32,27 +33,35 @@ public class SolvePuzzle extends AppCompatActivity { - public final static String COUNTRY_TO = "atorch.shortestpaths.COUNTRY_TO"; + // Saved instance state: enough to rebuild the puzzle after Android recreates this activity + // (for example after killing the app in the background, or when dark mode is switched on) + private static final String STATE_FROM = "atorch.shortestpaths.STATE_FROM"; + private static final String STATE_TO = "atorch.shortestpaths.STATE_TO"; + private static final String STATE_ROUTE = "atorch.shortestpaths.STATE_ROUTE"; - static TextView root_country; - static ImageView arrow; + private TextView root_country; + private ImageView arrow; + private AutoCompleteTextView country_input; - public static int level; + private int level; - static String[] congratulations_array; + private String[] congratulations_array; - static String[] countries; - static int country_from_index; - static int country_to_index; - static String country_from; - static String country_to; + private String[] countries; + private int country_from_index; + private int country_to_index; + private String country_from; + private String country_to; - static int path_length; - static int path_length_inner; // Equal to path_length - 2, i.e. number of countries user has to input - static int number_of_paths; - static String paths[][]; // Paths[i] is an array of country names - static boolean path_indicators[]; // When user's guess is consistent with paths[i], path_indicators[i] will be true - static int user_progress; // How far along path user has traveled + private int path_length; + private int path_length_inner; // Equal to path_length - 2, i.e. number of countries user has to input + private int number_of_paths; + private String[][] paths; // Paths[i] is an array of country names + private boolean[] path_indicators; // When user's guess is consistent with paths[i], path_indicators[i] will be true + private int user_progress; // How far along path user has traveled + private final ArrayList user_route = new ArrayList<>(); // Countries the user has correctly entered, in order + + private SQLiteDatabase db; public static final Random random = new Random(); @@ -139,137 +148,174 @@ private void reachedDestinationCountry(Context context, Resources res) { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - if (savedInstanceState != null) { - // TODO This is most likely wrong - country_to = savedInstanceState.getString(COUNTRY_TO); + // Always build the screen, including when Android recreates this activity + // (savedInstanceState != null), otherwise the user gets a blank screen + setContentView(R.layout.activity_solve_puzzle); + SystemBars.setUp(this); + + Intent intent = getIntent(); + if (intent != null) { + level = intent.getIntExtra(MainActivity.LEVEL, 0); + } + int path_length_lower = 3 + 2 * level; + int path_length_upper = 4 + 2 * level; + if (level == 2) { + path_length_upper = 20; // Not binding; current maximum in data is 9 + } + + final ActionBar actionBar = getSupportActionBar(); + actionBar.setHomeButtonEnabled(true); + actionBar.setDisplayHomeAsUpEnabled(true); + actionBar.setDisplayShowHomeEnabled(true); + + final Resources res = getResources(); + countries = res.getStringArray(R.array.countries); + congratulations_array = res.getStringArray(R.array.correct_guess_congratulations); + + final Context context = getApplicationContext(); + MySQLiteHelper mSQLiteHelper = new MySQLiteHelper(context); + db = mSQLiteHelper.getReadableDatabase(); + + ArrayList restored_route = null; + if (savedInstanceState != null && savedInstanceState.containsKey(STATE_FROM)) { + // Same puzzle as before Android recreated us + country_from_index = savedInstanceState.getInt(STATE_FROM); + country_to_index = savedInstanceState.getInt(STATE_TO); + restored_route = savedInstanceState.getStringArrayList(STATE_ROUTE); } else { - setContentView(R.layout.activity_solve_puzzle); - SystemBars.setUp(this); + Cursor c = getSummaryCursor(path_length_lower, path_length_upper, db); + country_from_index = c.getInt(c.getColumnIndexOrThrow(MySQLiteHelper.COL_FROM)); + country_to_index = c.getInt(c.getColumnIndexOrThrow(MySQLiteHelper.COL_TO)); + c.close(); + } + country_from = countries[country_from_index]; + country_to = countries[country_to_index]; + + root_country = (TextView) findViewById(R.id.countries_visited_root); + root_country.setText(country_from); + arrow = (ImageView) findViewById(R.id.countries_visited_arrow); + int id = getResources().getIdentifier("arrow", "drawable", getPackageName()); + arrow.setImageResource(id); + + Cursor c2 = getPathCursor(country_from_index, country_to_index, db); + number_of_paths = c2.getCount(); + String[][] paths_tokenized = new String[number_of_paths][]; + int i = 0; + while (c2.moveToNext()) { + paths_tokenized[i] = c2.getString(c2.getColumnIndexOrThrow(MySQLiteHelper.COL_PATH)).split(";"); + i++; + } + c2.close(); + // Every shortest path between the same two countries has the same length + path_length_inner = paths_tokenized[0].length; // Number of countries the user has to input + path_length = path_length_inner + 2; + paths = new String[number_of_paths][path_length_inner]; + for (i = 0; i < number_of_paths; i++) { + for (int j = 0; j < path_length_inner; j++) { + paths[i][j] = countries[Integer.parseInt(paths_tokenized[i][j])]; + } + } + path_indicators = new boolean[number_of_paths]; // Paths with which current answer is consistent + Arrays.fill(path_indicators, true); + user_progress = 0; + user_route.clear(); - user_progress = 0; + setPuzzleStatement(res); - Intent intent = getIntent(); - if (intent != null) { - level = intent.getIntExtra(MainActivity.LEVEL, 0); - } - int path_length_lower = 3 + 2 * level; - int path_length_upper = 4 + 2 * level; - if (level == 2) { - path_length_upper = 20; // Not binding; current maximum in data is 9 + Button buttonGiveUp = (Button) findViewById(R.id.button_give_up); + buttonGiveUp.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + openGiveUpDialog(v); } + }); - final ActionBar actionBar = getSupportActionBar(); - actionBar.setHomeButtonEnabled(true); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayShowHomeEnabled(true); + country_input = (AutoCompleteTextView) findViewById(R.id.autocomplete_country); - final Resources res = getResources(); - countries = res.getStringArray(R.array.countries); - congratulations_array = res.getStringArray(R.array.correct_guess_congratulations); - - final Context context = getApplicationContext(); - MySQLiteHelper mSQLiteHelper = new MySQLiteHelper(context); - SQLiteDatabase db = mSQLiteHelper.getReadableDatabase(); + final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, countries); + country_input.setAdapter(adapter); + country_input.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + countryEntered(adapter.getItem(position).toString()); + } + }); + + if (restored_route != null) { + // Put back the countries the user had already entered, without repeating + // the toasts or the database updates + for (String country : restored_route) { + if (!moveTo(country)) { + break; // Shouldn't happen: the route was valid when it was saved + } + } + } + } - Cursor c = getSummaryCursor(path_length_lower, path_length_upper, db); - country_from_index = c.getInt(c.getColumnIndexOrThrow(MySQLiteHelper.COL_FROM)); - country_to_index = c.getInt(c.getColumnIndexOrThrow(MySQLiteHelper.COL_TO)); - country_from = countries[country_from_index]; - country_to = countries[country_to_index]; - path_length = c.getInt(c.getColumnIndexOrThrow(MySQLiteHelper.COL_PATH_LENGTH)); - path_length_inner = path_length - 2; // Number of countries the user has to input - c.close(); + private void countryEntered(String user_answer) { + final Context context = getApplicationContext(); + final Resources res = getResources(); + if (moveTo(user_answer)) { + // TODO Put this in a fn, and call it for very last country seen + ContentValues content = new ContentValues(); + content.put(MySQLiteHelper.COL_COUNTRY_NAME, user_answer); + content.put(MySQLiteHelper.COL_COUNTRY_VISIT_COUNT, 1); // TODO Get previous count and increment + db.update(MySQLiteHelper.VISIT_COUNT_TABLE_NAME, content, MySQLiteHelper.COL_COUNTRY_NAME + " = ?", new String[]{user_answer}); + + if (user_progress < path_length_inner) { + String congratulations = congratulations_array[random.nextInt(congratulations_array.length)]; + Toast.makeText(context, congratulations, Toast.LENGTH_SHORT).show(); + } else { + String greatGuide = res.getString(R.string.great_guide); + Toast.makeText(context, greatGuide, Toast.LENGTH_LONG).show(); + } + } else { + Toast.makeText(context, "Sorry, " + user_answer + " won\'t help.", Toast.LENGTH_LONG).show(); + } + country_input.setText(""); + } - root_country = (TextView) findViewById(R.id.countries_visited_root); - root_country.setText(country_from); - arrow = (ImageView) findViewById(R.id.countries_visited_arrow); - int id = getResources().getIdentifier("arrow", "drawable", getPackageName()); - arrow.setImageResource(id); - - Cursor c2 = getPathCursor(country_from_index, country_to_index, db); - number_of_paths = c2.getCount(); - paths = new String[number_of_paths][path_length_inner]; - path_indicators = new boolean[number_of_paths]; // Paths with which current answer is consistent - Arrays.fill(path_indicators, true); - String[] current_path_tokenized; - int i = 0; - String current_path; - while (c2.moveToNext()) { - current_path = c2.getString(c2.getColumnIndexOrThrow(MySQLiteHelper.COL_PATH)); - current_path_tokenized = current_path.split(";"); - for (int j = 0; j < path_length_inner; j++) - paths[i][j] = countries[Integer.parseInt(current_path_tokenized[j])]; - i++; + /** + * Moves the user to country if it's the next country on a shortest path consistent with the + * countries entered so far, and updates the route on screen. Returns whether it was. + */ + private boolean moveTo(String country) { + boolean correct = false; + boolean[] new_path_indicators = new boolean[number_of_paths]; // Default to false + for (int i = 0; i < number_of_paths; i++) { + if (path_indicators[i] && paths[i][user_progress].equals(country)) { + correct = true; + new_path_indicators[i] = true; } - c2.close(); + } + if (!correct) { + return false; + } + user_progress++; + user_route.add(country); + path_indicators = new_path_indicators; + addCountryVisited(getApplicationContext(), country); - setPuzzleStatement(res); + if (user_progress >= path_length_inner) { + // Done solving puzzle: make country_input invisible; close keyboard + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(country_input.getWindowToken(), 0); + country_input.setVisibility(View.GONE); - Button buttonGiveUp = (Button) findViewById(R.id.button_give_up); - buttonGiveUp.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - openGiveUpDialog(v); - } - }); - - final AutoCompleteTextView country_input = (AutoCompleteTextView) findViewById(R.id.autocomplete_country); - - final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, countries); - country_input.setAdapter(adapter); - country_input.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - String user_answer = adapter.getItem(position).toString(); - boolean user_answer_is_correct = false; - boolean new_path_indicators[] = new boolean[number_of_paths]; // Default to false - for (int i = 0; i < number_of_paths; i++) { - if (path_indicators[i] && paths[i][user_progress] == user_answer) { - user_answer_is_correct = true; - new_path_indicators[i] = true; - } - } - if (user_answer_is_correct) { - user_progress++; - path_indicators = new_path_indicators; - addCountryVisited(context, user_answer); - - // TODO Put this in a fn, and call it for very last country seen - ContentValues content = new ContentValues(); - content.put(MySQLiteHelper.COL_COUNTRY_NAME, user_answer); - content.put(MySQLiteHelper.COL_COUNTRY_VISIT_COUNT, 1); // TODO Get previous count and increment - db.update(MySQLiteHelper.VISIT_COUNT_TABLE_NAME, content, MySQLiteHelper.COL_COUNTRY_NAME + " = ?", new String[]{user_answer}); - - if (user_progress < path_length_inner) { - String congratulations = congratulations_array[random.nextInt(congratulations_array.length)]; - Toast.makeText(context, congratulations, Toast.LENGTH_SHORT).show(); - } else { - // Done solving puzzle: make country_input invisible; close keyboard - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(country_input.getWindowToken(), 0); - country_input.setVisibility(View.GONE); - - reachedDestinationCountry(context, res); - - String greatGuide = res.getString(R.string.great_guide); - Toast.makeText(context, greatGuide, Toast.LENGTH_LONG).show(); - - LinearLayout buttons = (LinearLayout) findViewById(R.id.buttons); - buttons.setVisibility(View.VISIBLE); - } - } else { - Toast.makeText(context, "Sorry, " + user_answer + " won\'t help.", Toast.LENGTH_LONG).show(); - } - country_input.setText(""); - } - }); + reachedDestinationCountry(getApplicationContext(), getResources()); + + LinearLayout buttons = (LinearLayout) findViewById(R.id.buttons); + buttons.setVisibility(View.VISIBLE); } + return true; } @Override public void onSaveInstanceState(Bundle savedInstanceState) { - super.onSaveInstanceState(savedInstanceState); // TODO Am I using this? - savedInstanceState.putString(COUNTRY_TO, country_to); + super.onSaveInstanceState(savedInstanceState); + savedInstanceState.putInt(STATE_FROM, country_from_index); + savedInstanceState.putInt(STATE_TO, country_to_index); + savedInstanceState.putStringArrayList(STATE_ROUTE, new ArrayList<>(user_route)); } public void backToMain(View view) { @@ -279,7 +325,7 @@ public void backToMain(View view) { public void newPuzzle(View view) { Intent intent = new Intent(this, SolvePuzzle.class); - intent.putExtra(MainActivity.LEVEL, SolvePuzzle.level); + intent.putExtra(MainActivity.LEVEL, level); startActivity(intent); } diff --git a/app/src/test/java/atorch/shortestpaths/SolvePuzzleRecreationTest.java b/app/src/test/java/atorch/shortestpaths/SolvePuzzleRecreationTest.java new file mode 100644 index 0000000..da40cdf --- /dev/null +++ b/app/src/test/java/atorch/shortestpaths/SolvePuzzleRecreationTest.java @@ -0,0 +1,186 @@ +package atorch.shortestpaths; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import android.content.Intent; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.os.Bundle; +import android.view.View; +import android.widget.AutoCompleteTextView; +import android.widget.LinearLayout; +import android.widget.ListAdapter; +import android.widget.TextView; + +import androidx.core.text.HtmlCompat; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.android.controller.ActivityController; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Android can destroy and recreate SolvePuzzle at any time: when the app is killed in the background + * and the user comes back to it, or when a setting such as dark mode, font size or language changes. + * The user should get back the same puzzle, with the countries they've already entered, and be able + * to carry on solving it. + */ +@RunWith(RobolectricTestRunner.class) +public class SolvePuzzleRecreationTest { + + // Level 1 puzzles need 3 or 4 countries, so there's progress to keep after entering one + private static final int LEVEL = 1; + + private String[] countries; + + @Before + public void fillDatabase() { + // MainActivity fills the puzzle database the first time the app is opened + Robolectric.buildActivity(MainActivity.class).setup(); + countries = RuntimeEnvironment.getApplication().getResources().getStringArray(R.array.countries); + } + + @Test + public void puzzleSurvivesConfigurationChange() { + ActivityController controller = startPuzzle(); + String[] path = shortestPath(controller.get()); + enterCountry(controller.get(), path[0]); + PuzzleScreen before = PuzzleScreen.of(controller.get()); + + controller.recreate(); // e.g. the user switches dark mode on mid-puzzle + + assertSamePuzzleAndProgress(before, controller.get()); + assertCanCarryOn(controller.get(), path, before); + } + + @Test + public void puzzleSurvivesProcessDeath() { + ActivityController controller = startPuzzle(); + String[] path = shortestPath(controller.get()); + enterCountry(controller.get(), path[0]); + PuzzleScreen before = PuzzleScreen.of(controller.get()); + + // The user leaves the app, Android kills it, and later the user comes back: a brand new + // SolvePuzzle is created from nothing but the saved instance state + Bundle savedState = new Bundle(); + controller.pause().stop().saveInstanceState(savedState).destroy(); + ActivityController restored = + Robolectric.buildActivity(SolvePuzzle.class, puzzleIntent()).setup(savedState); + + assertSamePuzzleAndProgress(before, restored.get()); + assertCanCarryOn(restored.get(), path, before); + } + + private ActivityController startPuzzle() { + return Robolectric.buildActivity(SolvePuzzle.class, puzzleIntent()).setup(); + } + + private static Intent puzzleIntent() { + return new Intent(RuntimeEnvironment.getApplication(), SolvePuzzle.class) + .putExtra(MainActivity.LEVEL, LEVEL); + } + + private static void assertSamePuzzleAndProgress(PuzzleScreen before, SolvePuzzle activity) { + AutoCompleteTextView answerField = activity.findViewById(R.id.autocomplete_country); + assertNotNull("After recreation the puzzle screen is blank: there's no answer field", answerField); + assertEquals(View.VISIBLE, answerField.getVisibility()); + assertEquals("Different puzzle after recreation", before.statement, PuzzleScreen.of(activity).statement); + assertEquals("Countries entered so far were lost", before.route, PuzzleScreen.of(activity).route); + } + + /** The next country on the same shortest path is still accepted, and shows up on the route. */ + private static void assertCanCarryOn(SolvePuzzle activity, String[] path, PuzzleScreen before) { + enterCountry(activity, path[1]); + String[] route = PuzzleScreen.of(activity).route; + assertTrue("The second correct country wasn't accepted after recreation: " + Arrays.toString(route), + Arrays.asList(route).contains(path[1])); + assertEquals(before.route.length + 1, route.length); + } + + /** One of the shortest paths for the puzzle on screen, as the countries the user has to enter. */ + private String[] shortestPath(SolvePuzzle activity) { + PuzzleScreen screen = PuzzleScreen.of(activity); + String from = screen.route[0]; + String to = null; + String format = activity.getString(R.string.puzzle_statement_format_string); + for (String country : countries) { + String statement = HtmlCompat.fromHtml(String.format(format, from, country), + HtmlCompat.FROM_HTML_MODE_LEGACY).toString(); + if (statement.equals(screen.statement)) { + to = country; + } + } + assertNotNull("Couldn't work out the destination from: " + screen.statement, to); + + SQLiteDatabase db = new MySQLiteHelper(activity).getReadableDatabase(); + try (Cursor c = db.query(MySQLiteHelper.PATH_TABLE_NAME, new String[]{MySQLiteHelper.COL_PATH}, + MySQLiteHelper.COL_FROM + "=? and " + MySQLiteHelper.COL_TO + "=?", + new String[]{String.valueOf(indexOf(from)), String.valueOf(indexOf(to))}, + null, null, null, "1")) { + assertTrue("No path stored from " + from + " to " + to, c.moveToFirst()); + String[] indices = c.getString(0).split(";"); + String[] path = new String[indices.length]; + for (int i = 0; i < indices.length; i++) { + path[i] = countries[Integer.parseInt(indices[i])]; + } + assertTrue("Expected a level " + LEVEL + " puzzle with at least 3 countries to enter", path.length >= 3); + return path; + } + } + + private int indexOf(String country) { + int index = Arrays.asList(countries).indexOf(country); + assertTrue("Unknown country " + country, index >= 0); + return index; + } + + /** What the user does: pick a country from the answer field's suggestions. */ + private static void enterCountry(SolvePuzzle activity, String country) { + AutoCompleteTextView answerField = activity.findViewById(R.id.autocomplete_country); + assertNotNull("No answer field on screen", answerField); + ListAdapter suggestions = answerField.getAdapter(); + for (int position = 0; position < suggestions.getCount(); position++) { + if (country.equals(suggestions.getItem(position).toString())) { + answerField.getOnItemClickListener().onItemClick(null, answerField, position, position); + return; + } + } + throw new AssertionError(country + " isn't one of the suggestions"); + } + + /** The parts of the puzzle screen that should look the same after recreation. */ + private static final class PuzzleScreen { + final String statement; + final String[] route; // The start, then each country entered so far + + private PuzzleScreen(String statement, String[] route) { + this.statement = statement; + this.route = route; + } + + static PuzzleScreen of(SolvePuzzle activity) { + TextView statement = activity.findViewById(R.id.puzzle_statement); + LinearLayout countriesVisited = activity.findViewById(R.id.countries_visited); + assertNotNull("After recreation the puzzle screen is blank: there's no puzzle statement", statement); + assertNotNull("After recreation the puzzle screen is blank: there's no route", countriesVisited); + // The route is a column of country names with arrows between them + List route = new ArrayList<>(); + for (int i = 0; i < countriesVisited.getChildCount(); i++) { + View child = countriesVisited.getChildAt(i); + if (child instanceof TextView) { + route.add(((TextView) child).getText().toString()); + } + } + return new PuzzleScreen(statement.getText().toString(), route.toArray(new String[0])); + } + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a812f7b..0a1912c 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,9 +1,13 @@ [versions] agp = "9.5.0" appcompat = "1.8.0" +junit = "4.13.2" +robolectric = "4.17" [libraries] androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } +junit = { group = "junit", name = "junit", version.ref = "junit" } +robolectric = { group = "org.robolectric", name = "robolectric", version.ref = "robolectric" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" }