Build a Persistent Key-Value Shell with Tests and CI
Data Structure DesignModel answerLast updated
Design a single-class interactive key-value shell that saves to disk, handles bad input, logs errors, accepts new commands easily, and ships with unit tests, a README, and CI.
Task
Build a small interactive terminal program, implemented as one class, that acts as a persistent key-value store. A user types commands at a prompt and the program replies.
Required commands
| Command | Behavior |
|---|---|
add <key> <value> | Store a new entry |
get <key> | Print the value for a key |
delete <key> | Remove an entry |
list | Show every stored entry |
help | Describe the available commands |
exit | Leave the program |
Requirements
- Persistence: data is saved to a local file and reloaded on the next start.
- Validation: bad input (unknown commands, wrong argument counts, malformed text) must never crash the program. The user gets a clear message instead.
- Logging: errors are recorded through a logger.
- Extensibility: adding a new command should not require rewriting the existing dispatch logic.
- Tests: write thorough unit tests covering normal use, edge cases (duplicate keys, missing keys, malformed commands) and error handling.
- Project hygiene: include a README with setup steps and how to run the tests, plus a GitHub Actions workflow that runs the tests on every push.
Discussion points
Be ready to explain:
- The class design: what state it holds, its methods, and where its dependency boundaries lie.
- How you would refactor it to support subcommands or separate modules.
- The trade-offs you made, assuming you only had about 60 minutes.
State your policy on ambiguous cases (for example, what happens when add is used on an existing key) before you code them.
Hints
Hint 1
Keep the interactive loop trivial. Put all logic in a method that takes one line of text and returns the output string, so tests never need a real terminal.
Hint 2
Store commands in a registry (a dict from name to handler plus argument count and help text). Then adding a command is one registration call and the dispatcher stays unchanged.
Hint 3
Inject the file path, input stream, output stream and logger through the constructor so tests can use temp directories and in-memory streams.
Hint 4
Write the state file to a temp file and rename it over the original so a crash cannot leave a half-written file; handle a corrupt or missing file on startup.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the program into three layers, all inside one class (or a class plus tiny helpers), so each part is easy to test.
- Parsing and dispatch. A method
execute(line) -> strtokenizes the line, looks up the command in a registry, checks the argument count, runs the handler and returns text. All tests call this method directly. - Command handlers. Each command is a small method registered under a name with its arity, usage string and help text. A new command is one
register(...)call. The dispatcher never changes (open/closed principle). - I/O boundaries. The state-file path, input stream, output stream and logger are constructor parameters. Tests pass a temp path,
io.StringIOobjects and a capturing logger, so nothing relies on global state.
run() is only a loop: print the prompt, read a line, call execute, print the result. It holds no business logic.
Key design decisions
- Tokenizing with
shlex.splitlets values contain spaces when quoted:add greeting "hello world". Unbalanced quotes raiseValueError, which becomes a friendly "malformed input" message. - Command names are case-insensitive, keys stay case-sensitive.
- Duplicate
addis an error. Overwriting would need an explicitsetcommand. Say this policy out loud, since the spec is ambiguous. - Two error classes. A
CLIErrorrepresents an expected user mistake (missing key, duplicate key): show a message and log a warning. Any other exception is caught at the dispatch boundary, logged with a stack trace, and reported as a generic internal error. The REPL never dies on bad input. - State consistency. Mutate memory, then persist. If saving fails, roll the in-memory change back so memory and disk agree.
- Crash-safe saves. Write JSON to a temp file in the same directory, then
os.replaceit over the real file (atomic on POSIX and Windows). - Corrupt file on load. Rename it to
*.corrupt, log it, and start empty. This avoids silent data loss. - EOF and Ctrl-C end the loop cleanly.
Sketch
class CLIError(Exception): ...
@dataclass(frozen=True)
class Command:
name: str
handler: Callable[[List[str]], str]
arity: int # -1 means variadic
usage: str
help: str
class KeyValueCLI:
def __init__(self, path, stdin=sys.stdin, stdout=sys.stdout, logger=None):
self.path, self.stdin, self.stdout = path, stdin, stdout
self.log = logger or logging.getLogger("kvcli")
self.commands, self.running = {}, True
self.store = self._load()
self.register("add", self._add, 2, "add <key> <value>", "Add a new key")
# get, delete, list, help, exit registered the same way
def register(self, name, handler, arity, usage, help_text):
if name in self.commands:
raise ValueError(f"already registered: {name}")
self.commands[name] = Command(name, handler, arity, usage, help_text)
def execute(self, line):
try:
tokens = shlex.split(line)
except ValueError as e:
self.log.warning("malformed input %r: %s", line, e)
return "Error: malformed input (check quotes)"
if not tokens:
return ""
name, args = tokens[0].lower(), tokens[1:]
cmd = self.commands.get(name)
if cmd is None:
self.log.warning("unknown command %r", name)
return f"Error: unknown command '{name}'. Type 'help'."
if cmd.arity >= 0 and len(args) != cmd.arity:
return f"Usage: {cmd.usage}"
try:
return cmd.handler(args)
except CLIError as e:
self.log.warning("%s failed: %s", name, e)
return f"Error: {e}"
except Exception:
self.log.exception("unexpected error in %r", name)
return "Error: internal error (see log)"
Handlers raise CLIError for duplicates and missing keys. A shared _commit(rollback) saves to disk and calls rollback if saving fails. list sorts keys for deterministic output.
Complexity
add,get,delete: O(1) average for the dict, plus O(n) to rewrite the file.list: O(n log n) from sorting.- Space: O(n).
Rewriting the whole file on each mutation is the main shortcut taken for time.
Edge cases to cover
| Case | Expected behavior |
|---|---|
Duplicate add | Error, state unchanged |
get/delete on missing key | Error message |
| Wrong argument count | Usage line |
| Unknown command | Error, logged |
| Empty or whitespace line | No-op |
| Quoted value with spaces | Stored intact |
| Unbalanced quotes | Malformed-input error |
ADD vs add | Both work |
| EOF / Ctrl-C | Clean exit |
| Missing state file | Start empty |
| Corrupt state file | Backed up, start empty |
| Save fails | Memory rolled back |
Tests
Use pytest with tmp_path and StringIO:
- Happy path for each command, via
execute. - Persistence: create an instance,
add, build a second instance on the same path,getreturns the value. - Every row in the edge-case table above.
- Error handling: monkeypatch the save routine to raise, and assert the rollback and the generic error message; use
caplogto assert warnings and exceptions are logged. - Extensibility: register a custom command and run it; registering a duplicate name raises.
run()with scripted input ending inexit, and one ending in EOF.
README and CI
README: Python version, create a virtualenv, pip install -r requirements.txt, run with python kvcli.py data.json, run tests with pytest.
Workflow (.github/workflows/test.yml): trigger on push, steps actions/checkout, actions/setup-python, install dependencies, run pytest. Optionally a matrix of Python versions.
Refactoring for subcommands and modules
- Turn
Commandinto a small interface or base class, with one file per command group (kv,admin, ...). - Support dotted or nested names (
kv add,kv get) with a registry tree: the dispatcher walks tokens until it finds a leaf. - Extract a
Storageclass (load, save, atomic write) behind an interface so the store can be swapped for SQLite without touching handlers. - Keep
executeas the single entry point, so tests stay unchanged.
Trade-offs under 60 minutes
- Full-file rewrite instead of an append-only log or database.
- No file locking, so two concurrent processes can overwrite each other. Mention this as a known limit.
- String-only values, no TTL or types.
- One class rather than separate parser, store and shell classes. Mention where the seams would be.
Common mistakes
- Putting logic inside the input loop, which makes it untestable.
- Splitting on whitespace, which breaks values with spaces.
- Writing the file in place, risking corruption on a crash.
- Catching bare exceptions and hiding them without logging.
- Leaving memory modified after a failed save.
- Not stating the duplicate-key policy.