1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
|
# deck-it - tests for the Xbox module
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import json
import os
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import unittest
import deckit.modules.xbox as xb
PRESENCE = {"xuid": "1", "state": "Online", "devices": [{"type": "Scarlett", "titles": [
{"id": "750323071", "name": "Home", "placement": "Background", "state": "Active"},
{"id": "1234", "name": "Some Game", "placement": "Full", "state": "Active",
"activity": {"richPresence": "Ranked match"}}]}]}
CONSOLES = {"status": {"errorCode": "OK"}, "result": [
{"id": "CON1", "name": "Living room", "consoleType": "XboxSeriesX", "powerState": "On",
"storageDevices": [{"storageDeviceName": "Internal", "freeSpaceBytes": 4e11, "totalSpaceBytes": 1e12}]}]}
PROFILE = {"profileUsers": [{"id": "1", "settings": [
{"id": "Gamertag", "value": "Player"}, {"id": "GameDisplayPicRaw", "value": "https://img.example.org/p.png"},
{"id": "Gamerscore", "value": "12345"}]}]}
HISTORY = {"titles": [
{"titleId": "1234", "name": "Some Game", "type": "Game", "displayImage": "https://img.example.org/c.png",
"titleHistory": {"lastTimePlayed": "2026-11-16T10:00:00Z"},
"achievement": {"currentAchievements": 5, "totalAchievements": 50, "currentGamerscore": 100,
"totalGamerscore": 1000, "progressPercentage": 10.0}},
{"titleId": "99", "name": "Video App", "type": "App", "displayImage": None}]}
STATS = {"statlistscollection": [{"arrangebyfieldid": "1", "stats": [
{"titleid": "1234", "name": "MinutesPlayed", "value": "185"}]}]}
ACHIEVEMENTS = {"achievements": [{"name": "First", "description": "Do a thing",
"mediaAssets": [{"url": "https://img.example.org/a.png"}], "titleAssociations": [{"name": "Some Game"}],
"rewards": [{"type": "Gamerscore", "value": "15"}], "progression": {"timeUnlocked": "2026-11-15T20:00:00Z"}}]}
FRIENDS = {"people": [
{"gamertag": "zed", "displayPicRaw": "z.png", "presenceState": "Offline", "presenceText": "Offline", "isFavorite": True},
{"gamertag": "bob", "displayPicRaw": "b.png", "presenceState": "Online", "presenceText": "Some Game", "isFavorite": False},
{"gamertag": "amy", "displayPicRaw": "a.png", "presenceState": "Online", "presenceText": "Home", "isFavorite": True}]}
XSTS = {"Token": "XT", "DisplayClaims": {"xui": [{"uhs": "UHS", "xid": "1"}]}}
class Fake:
"""Answers by URL; `fail` maps a URL fragment to an HttpError to raise once."""
def __init__(self, **over):
self.calls, self.fail = [], {}
self.answers = {
"/oauth2/v2.0/token": {"access_token": "AT", "refresh_token": "RT2"},
"/oauth2/v2.0/devicecode": {"user_code": "ABCD-1234", "verification_uri": "https://microsoft.com/devicelogin",
"expires_in": 900, "interval": 0, "device_code": "DEV"},
"user.auth.xboxlive.com": {"Token": "UT"},
"xsts.auth.xboxlive.com": XSTS,
"userpresence": PRESENCE,
"/lists/devices": CONSOLES,
"profile.xboxlive.com": PROFILE,
"titlehistory": HISTORY,
"titleid(": {"titles": [{"type": "Game"}]},
"userstats": STATS,
"achievements.xboxlive.com": ACHIEVEMENTS,
"peoplehub": FRIENDS,
"/commands": {"status": {"errorCode": "OK"}, "opId": "op"},
}
self.answers.update(over)
def __call__(self, url, data=None, headers=None, timeout=10):
self.calls.append((url, data, headers or {}))
for frag, err in list(self.fail.items()):
if frag in url:
del self.fail[frag]
raise err
for frag, answer in self.answers.items():
if frag in url:
return answer
raise AssertionError(f"unexpected url {url}")
def urls(self, frag):
return [c for c in self.calls if frag in c[0]]
class Base(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
self.addCleanup(self.dir.cleanup)
self.token = Path(self.dir.name) / "cfg" / "xbox-token.json"
self.status = Path(self.dir.name) / "status.xbox"
self.fake = Fake()
def xbox(self, signed_in=True, client_id="CID"):
if signed_in:
self.token.parent.mkdir(parents=True, exist_ok=True)
self.token.write_text(json.dumps({"refresh_token": "RT"}))
return xb.Xbox({"xbox": {"client_id": client_id}}, self.fake, self.token, self.status)
class Auth(Base):
def test_chain_builds_the_xbl3_header(self):
x = self.xbox()
x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
url, data, headers = self.fake.urls("userpresence")[0]
self.assertEqual(headers["Authorization"], "XBL3.0 x=UHS;XT")
self.assertEqual(headers["x-xbl-contract-version"], "3")
user = self.fake.urls("user.auth")[0][1]
self.assertEqual(user["Properties"]["RpsTicket"], "d=AT")
self.assertEqual(x.auth["xuid"], "1")
def test_a_rotated_refresh_token_is_saved_private(self):
x = self.xbox()
x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
self.assertEqual(json.loads(self.token.read_text()), {"refresh_token": "RT2"})
self.assertEqual(os.stat(self.token).st_mode & 0o777, 0o600)
def test_a_401_renews_once(self):
x = self.xbox()
x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
self.fake.fail["userpresence"] = xb.HttpError(401, {})
x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
self.assertEqual(len(self.fake.urls("xsts.auth")), 2)
def test_a_refused_refresh_token_signs_out(self):
x = self.xbox()
self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "invalid_grant"})
with self.assertRaises(xb.SignedOut):
x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
self.assertFalse(self.token.exists())
self.assertIsNone(x.refresh)
class Summaries(unittest.TestCase):
def test_foreground_is_the_full_placement_title(self):
self.assertEqual(xb.foreground(PRESENCE),
{"id": "1234", "name": "Some Game", "rich": "Ranked match", "device": "Scarlett"})
self.assertIsNone(xb.foreground({"state": "Offline"}))
def test_foreground_takes_a_list_activity_too(self):
p = {"devices": [{"titles": [{"id": 7, "name": "X", "placement": "Full", "activity": [{"richPresence": "Lobby"}]}]}]}
self.assertEqual(xb.foreground(p)["rich"], "Lobby")
self.assertEqual(xb.foreground(p)["id"], "7")
def test_presence_has_last_seen(self):
p = xb.summarize_presence({"state": "Offline", "lastSeen": {"titleName": "Home", "timestamp": "2026-11-15T22:00:00Z"}})
self.assertEqual(p, {"state": "Offline", "title": None,
"last_seen": {"title": "Home", "when": "2026-11-15T22:00:00Z"}})
def test_profile(self):
self.assertEqual(xb.summarize_profile(PROFILE),
{"gamertag": "Player", "pic": "https://img.example.org/p.png", "gamerscore": 12345})
def test_consoles(self):
c = xb.summarize_consoles(CONSOLES)[0]
self.assertEqual((c["id"], c["name"], c["power"]), ("CON1", "Living room", "On"))
self.assertEqual(c["storage"], [{"name": "Internal", "free": 4e11, "total": 1e12}])
def test_minutes_and_titles(self):
minutes = xb.minutes_played(STATS)
self.assertEqual(minutes, {"1234": 185})
t = xb.summarize_titles(HISTORY, minutes)
self.assertEqual(t[0]["minutes"], 185)
self.assertEqual(t[0]["achievements"], {"done": 5, "total": 50, "score": 100, "max": 1000, "pct": 10.0})
self.assertEqual((t[1]["type"], t[1]["minutes"]), ("App", None))
def test_achievements(self):
a = xb.summarize_achievements(ACHIEVEMENTS)[0]
self.assertEqual(a, {"name": "First", "description": "Do a thing", "icon": "https://img.example.org/a.png",
"score": 15, "title": "Some Game", "unlocked": "2026-11-15T20:00:00Z"})
def test_friends_online_then_favourite_then_name(self):
self.assertEqual([f["gamertag"] for f in xb.summarize_friends(FRIENDS)], ["amy", "bob", "zed"])
if __name__ == "__main__":
unittest.main()
|