Skip to content

Commit

Permalink
updates and fixes to test
Browse files Browse the repository at this point in the history
  • Loading branch information
kavigupta committed Jan 18, 2025
1 parent 3c67048 commit 88d746f
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 14 deletions.
4 changes: 2 additions & 2 deletions react/src/quiz/statistics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ async function getUnreportedSeedVersions(user: string, secureID: string, wholeHi
}
const response = await fetch(`${endpoint}/juxtastat_infinite/has_infinite_stats`, {
method: 'POST',
body: JSON.stringify({ user, secureID, seed_versions: seedVersions }),
body: JSON.stringify({ user, secureID, seedVersions }),
headers: {
'Content-Type': 'application/json',
},
Expand All @@ -96,7 +96,7 @@ async function reportToServerInfinite(wholeHistory: QuizHistory): Promise<boolea
const dayStats = wholeHistory[key]
await fetch(`${endpoint}/juxtastat_infinite/store_user_stats`, {
method: 'POST',
body: JSON.stringify({ user, secureID, seed, version, day_stats: dayStats.correct_pattern }),
body: JSON.stringify({ user, secureID, seed, version, corrects: dayStats.correct_pattern }),
headers: {
'Content-Type': 'application/json',
},
Expand Down
32 changes: 28 additions & 4 deletions react/test/quiz_infinite_test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Selector } from 'testcafe'

import { clickButton, clickButtons, withMockedClipboard } from './quiz_test_utils'
import { runQuery } from './quiz_test_template'
import { clickButton, clickButtons, quizFixture, withMockedClipboard } from './quiz_test_utils'
import {
target,
urbanstatsFixture,
safeReload,
waitForQuizLoading,
} from './test_utils'
Expand Down Expand Up @@ -31,8 +31,16 @@ async function correctIncorrect(t: TestController): Promise<boolean[]> {
return result
}

const localStorageDefault = { persistent_id: '000000000000007', secure_id: '00000003' }

async function completeCorrectAnswerSequence(t: TestController, alreadyKnownAnswers: string[]): Promise<string[]> {
await t.eval(() => { localStorage.clear() })
await t.eval(() => {
localStorage.clear()
for (const key of Object.keys(localStorageDefault)) {
localStorage.setItem(key, localStorageDefault[key])
}
}, { dependencies: { localStorageDefault } })
await t.wait(100)
await safeReload(t)
await waitForQuizLoading(t)
await clickButtons(t, alreadyKnownAnswers)
Expand Down Expand Up @@ -61,8 +69,15 @@ async function completeCorrectAnswerSequence(t: TestController, alreadyKnownAnsw
return correctAnswers
}

const seed = 0xdeadbeef00
const param = '#mode=infinite&seed=deadbeef00&v=0'
urbanstatsFixture('generate link', `${target}/quiz.html${param}`)
quizFixture(
'generate link',
`${target}/quiz.html${param}`,
localStorageDefault,
``,
'desktop',
)

let correctAnswerSequence: string[]

Expand Down Expand Up @@ -109,6 +124,10 @@ async function getLives(): Promise<Emoji[]> {
return result
}

function juxtastatInfiniteTable(): Promise<string> {
return runQuery('SELECT user, seed, hex(corrects), score, num_answers from JuxtaStatInfiniteStats')
}

test('display-life-lost', async (t) => {
await t.expect(await getLives()).eql(['Y', 'Y', 'Y'])
await provideAnswers(t, 0, [false])
Expand All @@ -117,13 +136,18 @@ test('display-life-lost', async (t) => {
await t.expect(await getLives()).eql(['Y', 'N', 'N'])
await provideAnswers(t, 2, [false])
await t.expect(await correctIncorrect(t)).eql([false, false, false])
await t.expect(await juxtastatInfiniteTable()).eql(`7|${seed}|00|0|3`)
})

test('display-life-gained', async (t) => {
await provideAnswers(t, 0, [true, true, true, true])
await t.expect(await getLives()).eql(['Y', 'Y', 'Y'])
await provideAnswers(t, 4, [true])
await t.expect(await getLives()).eql(['Y', 'Y', 'Y', 'Y'])
await provideAnswers(t, 5, [false, false, false, false])
await t.expect(await correctIncorrect(t)).eql([true, true, true, true, true, false, false, false, false])
// low bit order first: 11111000 0. This becomes 1F 00
await t.expect(await juxtastatInfiniteTable()).eql(`7|${seed}|1F00|4|9`)
})

test('display-life-regained', async (t) => {
Expand Down
2 changes: 1 addition & 1 deletion react/test/quiz_test_template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { ClientFunction, Selector } from 'testcafe'
import { clickButton, clickButtons, quizFixture, quizScreencap, tempfileName, withMockedClipboard } from './quiz_test_utils'
import { target, mostRecentDownloadPath, safeReload, screencap, getLocation } from './test_utils'

async function runQuery(query: string): Promise<string> {
export async function runQuery(query: string): Promise<string> {
// dump given query to a string
const commandLine = `sqlite3 ../urbanstats-persistent-data/db.sqlite3 "${query}"`
const result = await promisify(exec)(commandLine)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def table():
# juxtastat infinite
c.execute(
"""CREATE TABLE IF NOT EXISTS JuxtaStatInfiniteStats
(user integer, seed integer, version integer, corrects varbinary(128), score integer, time integer, PRIMARY KEY (user, seed, version))"""
(user integer, seed integer, version integer, corrects varbinary(128), score integer, num_answers integer, time integer, PRIMARY KEY (user, seed, version))"""
)

# user to domain name
Expand Down Expand Up @@ -175,7 +175,7 @@ def has_infinite_stats(user, seeds_versions):
)
results = c.fetchall()
results = set(results)
return [(int(seed, 16), version) in results for seed, version in seeds_versions]
return [(seed, version) in results for seed, version in seeds_versions]


def store_user_stats_infinite(user, seed, version, corrects: List[bool]):
Expand All @@ -184,11 +184,19 @@ def store_user_stats_infinite(user, seed, version, corrects: List[bool]):
conn, c = table()
# ignore latest day here, it is up to the client to filter out old stats
# we want to be able to update stats for old days
corrects = corrects_to_bytes(corrects)
correctBytes = corrects_to_bytes(corrects)
time_unix_millis = round(time.time() * 1000)
c.execute(
"INSERT OR REPLACE INTO JuxtaStatInfiniteStats VALUES (?, ?, ?, ?, ?, ?)",
(user, seed, version, corrects, sum(corrects), time_unix_millis),
"INSERT OR REPLACE INTO JuxtaStatInfiniteStats VALUES (?, ?, ?, ?, ?, ?, ?)",
(
user,
seed,
version,
correctBytes,
sum(corrects),
len(corrects),
time_unix_millis,
),
)
conn.commit()

Expand Down
10 changes: 8 additions & 2 deletions urbanstats-persistent-data/urbanstats_persistent_data/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ def get_authenticated_user(additional_required_params=()):
required_params = ["user", "secureID"] + list(additional_required_params)

if not all([param in form for param in required_params]):
print("NEEDS PARAMS", required_params, "GOT", form.keys())
return False, (
flask.jsonify(
{
Expand All @@ -103,8 +104,10 @@ def authenticate(fields):
def decorator(fn):
@functools.wraps(fn)
def wrapper():
print("AUTHENTICATE", flask_form())
success, error = get_authenticated_user(fields)
if not success:
print("AUTHENTICATE ERROR", error)
return error
return fn()

Expand Down Expand Up @@ -149,11 +152,14 @@ def juxtastat_store_user_stats_request():


@app.route("/juxtastat_infinite/has_infinite_stats", methods=["POST"])
@authenticate(["seedsVersions"])
@authenticate(["seedVersions"])
def juxtastat_infinite_has_infinite_stats_request():
form = flask_form()
print("HAS INFINITE STATS", form)
res = dict(has=has_infinite_stats(form["user"], form["seedVersions"]))
print("HAS INFINITE STATS", res)
return flask.jsonify(
dict(has=has_infinite_stats(form["user"], form["seedsVersions"]))
res
)


Expand Down

0 comments on commit 88d746f

Please sign in to comment.