1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6declare(strict_types=1);
7
8namespace Tests\Middleware;
9
10use App\Models\OAuth\Client;
11use App\Models\User;
12use Carbon\Carbon;
13use Tests\TestCase;
14
15class UpdateUserInfoTest extends TestCase
16{
17 public function testClientBasic(): void
18 {
19 $user = User::factory()->create(['user_lastvisit' => Carbon::now()->subDays(1)]);
20 $this->expectCountChange(fn () => $user->userCountryHistory()->count(), 1);
21
22 $this->actAsClientUser($user);
23 $this->get(route('api.me'));
24
25 $this->assertTrue($user->fresh()->user_lastvisit->addSeconds(5)->isFuture());
26 }
27
28 public function testClientCountryHistoryTwiceIncrementCountAndNoDuplicateError(): void
29 {
30 $user = User::factory()->create(['user_lastvisit' => Carbon::now()->subDays(1)]);
31
32 $countryAcronym = 'JP';
33 $user->userCountryHistory()->create([
34 'country_acronym' => $countryAcronym,
35 'year_month' => format_month_column(new \DateTime()),
36 ]);
37
38 $this->expectCountChange(fn () => $user->userCountryHistory()->count(), 0);
39 $this->expectCountChange(fn () => $user->userCountryHistory()->first()->count, 1);
40
41 $this->actAsClientUser($user);
42 $this
43 ->withHeaders(['cf-ipcountry' => $countryAcronym])
44 ->get(route('api.me'));
45 }
46
47 public function testClientDifferentCountry(): void
48 {
49 $user = User::factory()->create(['user_lastvisit' => Carbon::now()->subDays(1)]);
50
51 $user->userCountryHistory()->create([
52 'country_acronym' => 'JP',
53 'year_month' => format_month_column(new \DateTime()),
54 ]);
55
56 $this->expectCountChange(fn () => $user->userCountryHistory()->count(), 1);
57
58 $this->actAsClientUser($user);
59 $this
60 ->withHeaders(['cf-ipcountry' => 'AU'])
61 ->get(route('api.me'));
62 }
63
64 private function actAsClientUser(User $user): void
65 {
66 $client = Client::factory()->create(['password_client' => true]);
67 $this->actAsScopedUser($user, ['*'], $client);
68 }
69}