"""Tests for the Steam ownership marker.""" import contextlib import io import os import sys import tempfile import unittest from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) import check_ownership import db class OwnershipTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.path = os.path.join(self.tmp.name, "own.db") con = db.connect(self.path) db.init(con) con.executemany( "INSERT INTO games (appid, name, type) VALUES (?,?,?)", [(1, "A", "game"), (2, "B", "game"), (3, "C", "dlc")]) con.commit() con.close() def _run(self, *extra): argv = ["check_ownership.py", "--db", self.path, *extra] with mock.patch.object(sys, "argv", argv), \ mock.patch.object(check_ownership.steam_api, "has_key", return_value=True), \ mock.patch.object(check_ownership.steam_api, "steam_id", return_value="765"), \ mock.patch.object(check_ownership.steam_api, "owned_games", return_value=[{"appid": 1}, {"appid": 3}]), \ contextlib.redirect_stdout(io.StringIO()): return check_ownership.main() def test_marks_owned_and_shared(self): self.assertEqual(self._run(), 0) con = db.connect(self.path) try: rows = {row["appid"]: row["owned"] for row in con.execute( "SELECT appid, owned FROM game_ownership")} finally: con.close() self.assertEqual(rows, {1: 1, 2: 0}) def test_dry_run_does_not_write(self): self.assertEqual(self._run("--dry-run"), 0) con = db.connect(self.path) try: count = con.execute("SELECT COUNT(*) FROM game_ownership").fetchone()[0] finally: con.close() self.assertEqual(count, 0) def test_requires_key(self): with mock.patch.object(check_ownership.steam_api, "has_key", return_value=False), \ mock.patch.object(sys, "argv", ["check_ownership.py", "--db", self.path]), \ contextlib.redirect_stderr(io.StringIO()): self.assertEqual(check_ownership.main(), 1) if __name__ == "__main__": unittest.main()