File size: 10,346 Bytes
d6ea71e |
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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
import json
import os
import shutil
import sys
import unittest
from importlib import reload
import pytest
import socceraction.data.statsbomb as sb
from py.path import local
from pytest import fixture
from socceraction.data.base import ParseError
from socceraction.data.statsbomb import (
StatsBombCompetitionSchema,
StatsBombEventSchema,
StatsBombGameSchema,
StatsBombPlayerSchema,
StatsBombTeamSchema,
)
@fixture(scope="module", params=["local", "remote"])
def SBL(request) -> sb.StatsBombLoader: # type: ignore # noqa: ANN001
"""Create a StatsBombLoader instance."""
data_dir = os.path.join(os.path.dirname(__file__), os.pardir, "datasets", "statsbomb", "raw")
return sb.StatsBombLoader(getter=request.param, root=data_dir)
# Test init ##################################################################
def test_load_remote() -> None:
"""It can load remote data."""
SBL = sb.StatsBombLoader(getter="remote")
assert SBL._creds is not None
def test_load_local() -> None:
"""It can load local data."""
data_dir = os.path.join(os.path.dirname(__file__), os.pardir, "datasets", "statsbomb", "raw")
SBL = sb.StatsBombLoader(getter="local", root=str(data_dir))
assert SBL._root is not None
def test_load_invalid_source() -> None:
"""It raises an error if the source is not ``remote`` or ``local``."""
with pytest.raises(ValueError):
sb.StatsBombLoader(getter="foo")
def test_load_local_missing_root() -> None:
"""It raises an error if the root is not provided when loading local data."""
with pytest.raises(ValueError):
sb.StatsBombLoader(getter="local")
class TestWithoutStatsBombPy(unittest.TestCase):
def setUp(self) -> None:
self._temp_sbpy = sys.modules.get("statsbombpy")
sys.modules["statsbombpy"] = None # type: ignore
reload(sys.modules["socceraction.data.statsbomb.loader"])
def tearDown(self) -> None:
sys.modules["statsbombpy"] = self._temp_sbpy # type: ignore
reload(sys.modules["socceraction.data.statsbomb.loader"])
def tests_load_without_statsbombpy(self) -> None:
"""It raises an error upon initialization of a remote loader if statsbombpy is not installed."""
with pytest.raises(ImportError):
sb.StatsBombLoader(getter="remote")
# Test competitions ##########################################################
def test_competitions(SBL: sb.StatsBombLoader) -> None:
"""It loads a DataFrame with available competitions."""
df_competitions = SBL.competitions()
assert len(df_competitions) > 0
StatsBombCompetitionSchema.validate(df_competitions)
def test_no_competitions(tmpdir: local) -> None:
"""It returns an empty DataFrame when no competitions are available."""
p = tmpdir.join("competitions.json")
p.write(json.dumps([]))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
df_competitions = SBL.competitions()
assert len(df_competitions) == 0
StatsBombCompetitionSchema.validate(df_competitions)
def test_invalid_competitions(tmpdir: local) -> None:
"""It raises an error if the competitions.json file is invalid."""
p = tmpdir.join("competitions.json")
p.write(json.dumps({"this is wrong": 1}))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
with pytest.raises(ParseError):
SBL.competitions()
# Test games #################################################################
def test_games(SBL: sb.StatsBombLoader) -> None:
"""It loads a DataFrame with available competitions."""
df_games = SBL.games(43, 3) # World Cup, 2018
assert len(df_games) == 64
StatsBombGameSchema.validate(df_games)
def test_no_games(tmpdir: local) -> None:
"""It returns an empty DataFrame when no games are available."""
p = tmpdir.mkdir("matches").mkdir("11").join("1.json")
p.write(json.dumps([]))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
df_games = SBL.games(11, 1)
assert len(df_games) == 0
StatsBombGameSchema.validate(df_games)
def test_invalid_games(tmpdir: local) -> None:
"""It raises an error if the json file is invalid."""
p = tmpdir.mkdir("matches").mkdir("11").join("1.json")
p.write(json.dumps({"this is wrong": 1}))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
with pytest.raises(ParseError):
SBL.games(11, 1)
# Test teams #################################################################
def test_teams(SBL: sb.StatsBombLoader) -> None:
"""It loads a DataFrame with both teams that participated in a game."""
df_teams = SBL.teams(7584)
assert len(df_teams) == 2
StatsBombTeamSchema.validate(df_teams)
def test_no_teams(tmpdir: local) -> None:
"""It raises an error when no lineups are available for each team."""
p = tmpdir.mkdir("lineups").join("7584.json")
p.write(json.dumps([]))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
with pytest.raises(ParseError):
SBL.teams(7584)
def test_invalid_teams(tmpdir: local) -> None:
"""It raises an error if the json file is invalid."""
p = tmpdir.mkdir("lineups").join("7584.json")
p.write(json.dumps({"this is wrong": 1}))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
with pytest.raises(ParseError):
SBL.teams(7584)
# Test player ################################################################
def test_players(SBL: sb.StatsBombLoader) -> None:
"""It loads a DataFrame with all players that participated in a game."""
df_players = SBL.players(7584)
assert len(df_players) == 26
StatsBombPlayerSchema.validate(df_players)
def test_no_players(tmpdir: local) -> None:
"""It raises an error when no lineups are available for both teams."""
p = tmpdir.mkdir("lineups").join("7584.json")
p.write(json.dumps([]))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
with pytest.raises(ParseError):
SBL.players(7584)
def test_invalid_players(tmpdir: local) -> None:
"""It raises an error if the json file is invalid."""
p = tmpdir.mkdir("lineups").join("7584.json")
p.write(json.dumps({"this is wrong": 1}))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
with pytest.raises(ParseError):
SBL.players(7584)
# Test events ################################################################
def test_events(SBL: sb.StatsBombLoader) -> None:
"""It loads a DataFrame with all events during a game."""
df_events = SBL.events(7584)
assert len(df_events) > 0
StatsBombEventSchema.validate(df_events)
def test_no_events(tmpdir: local) -> None:
"""It returns an empty DataFrame when no events are available."""
p = tmpdir.mkdir("events").join("7584.json")
p.write(json.dumps([]))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
df_events = SBL.events(7584)
assert len(df_events) == 0
StatsBombEventSchema.validate(df_events)
def test_invalid_events(tmpdir: local) -> None:
"""It raises an error if the json file is invalid."""
p = tmpdir.mkdir("events").join("7584.json")
p.write(json.dumps({"this is wrong": 1}))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
with pytest.raises(ParseError):
SBL.events(7584)
# Test 360 frames ##############################################################
def test_frames(SBL: sb.StatsBombLoader) -> None:
"""It loads a DataFrame with all 360 frames recorded during a game."""
df_frames = SBL.events(3788741, load_360=True)
assert len(df_frames) > 0
StatsBombEventSchema.validate(df_frames)
assert "visible_area_360" in df_frames.columns
assert "freeze_frame_360" in df_frames.columns
def test_no_frames_empty(tmpdir: local) -> None:
"""It just returns the events DataFrame when no 360 frames are available."""
tmpdir.mkdir("events")
datadir = os.path.join(os.path.dirname(__file__), os.pardir, "datasets", "statsbomb", "raw")
shutil.copy(
os.path.join(datadir, "events/7584.json"),
os.path.join(tmpdir, "events/7584.json"),
)
p = tmpdir.mkdir("three-sixty").join("7584.json")
p.write(json.dumps([]))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
df_frames = SBL.events(7584, load_360=True)
assert len(df_frames) > 0
assert "visible_area_360" in df_frames.columns
assert "freeze_frame_360" in df_frames.columns
StatsBombEventSchema.validate(df_frames)
def test_invalid_frames(tmpdir: local) -> None:
"""It raises an error if the json file is invalid."""
tmpdir.mkdir("events")
datadir = os.path.join(os.path.dirname(__file__), os.pardir, "datasets", "statsbomb", "raw")
shutil.copy(
os.path.join(datadir, "events/7584.json"),
os.path.join(tmpdir, "events/7584.json"),
)
p = tmpdir.mkdir("three-sixty").join("7584.json")
p.write(json.dumps({"this is wrong": 1}))
SBL = sb.StatsBombLoader(root=str(tmpdir), getter="local")
with pytest.raises(ParseError):
SBL.events(7584, load_360=True)
# Test extract_player_games ##################################################
def test_extract_player_games(SBL: sb.StatsBombLoader) -> None:
df_events = SBL.events(7584)
df_player_games = sb.extract_player_games(df_events)
assert len(df_player_games) == 26
assert len(df_player_games.player_name.unique()) == 26
assert set(df_player_games.team_name) == {"Belgium", "Japan"}
assert df_player_games.minutes_played.sum() == 22 * 96
def test_minutes_played(SBL: sb.StatsBombLoader) -> None:
# Injury time should be added
df_players = SBL.players(7584).set_index("player_id")
assert df_players.at[5630, "minutes_played"] == 64 + 1
assert df_players.at[3296, "minutes_played"] == 96 - (64 + 1)
# Penalty shoot-outs should no be added
df_players = SBL.players(7581).set_index("player_id")
assert df_players.minutes_played.sum() / 22 == 127
# COL - JAP: red card in '2
df_players = SBL.players(7541).set_index("player_id")
assert df_players.at[5685, "minutes_played"] == 2
# GER - SWE: double yellow card in '80 + 2' injury time
df_players = SBL.players(7551).set_index("player_id")
assert df_players.at[5578, "minutes_played"] == 82
|