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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# frozen_string_literal: true

require_relative "test_helper"

require "minitest/autorun"
require "rack/test"

require_relative "../lib/rank_king/web"

class TestWeb < Minitest::Test
  include Rack::Test::Methods

  def app = RankKing::Web.app

  LOGIN = "alpha@example.com"

  def setup
    header "Remote-User", LOGIN
    RankKing::DB[:results].delete
    RankKing::DB[:axes].delete
    RankKing::DB[:items].delete
    RankKing::DB[:lists].delete
    RankKing::DB[:users].delete
  end

  def test_root_shows_empty_state
    get "/"
    assert last_response.ok?
    assert_includes last_response.body, "No lists yet."
  end

  def test_create_list
    create_list(name: "Foods", items: "Pizza\nSushi\nTacos", axes: %w[Taste Value])
    assert last_response.redirect?

    list = RankKing::DB[:lists].first
    assert_equal "Foods", list[:name]

    items = RankKing::DB[:items].where(list_id: list[:id]).map { |i| i[:name] }
    assert_equal %w[Pizza Sushi Tacos], items

    axes = RankKing::DB[:axes].where(list_id: list[:id]).map { |a| a[:name] }
    assert_equal %w[Taste Value], axes
  end

  def test_create_list_rejects_empty_name
    create_list(name: "  ", items: "A\nB")
    assert_equal 422, last_response.status
  end

  def test_create_list_rejects_fewer_than_two_items
    create_list(name: "Solo", items: "OnlyOne")
    assert_equal 422, last_response.status
    assert_equal "A list needs at least two items.\n", last_response.body
  end

  def test_create_list_without_axes
    create_list(name: "Simple", items: "A\nB", axes: [""])
    assert last_response.redirect?

    list = RankKing::DB[:lists].first
    assert_equal 0, RankKing::DB[:axes].where(list_id: list[:id]).count
  end

  def test_show_list
    create_list(name: "Foods", items: "Pizza\nSushi", axes: %w[Taste])
    list = RankKing::DB[:lists].first

    get "/lists/#{list[:id]}"
    assert last_response.ok?
    assert_includes last_response.body, "Foods"
    assert_includes last_response.body, "Pizza"
    assert_includes last_response.body, "Sushi"
    assert_includes last_response.body, "Taste"
  end

  def test_show_list_404_for_nonexistent
    get "/lists/999999"
    assert_equal 404, last_response.status
  end

  def test_record_result
    create_list(name: "Foods", items: "Pizza\nSushi", axes: %w[Taste])
    list = RankKing::DB[:lists].first
    items = RankKing::DB[:items].where(list_id: list[:id]).all
    axis = RankKing::DB[:axes].first(list_id: list[:id])

    csrf_post "/lists/#{list[:id]}/results", {
      axis_id: axis[:id],
      winner_id: items[0][:id],
      loser_id: items[1][:id],
    }, from: "/lists/#{list[:id]}/axes/#{axis[:id]}/compare"
    assert last_response.redirect?

    result = RankKing::DB[:results].first
    assert_equal axis[:id], result[:axis_id]
    assert_equal items[0][:id], result[:winner_id]
    assert_equal items[1][:id], result[:loser_id]
  end

  def test_record_result_rejects_same_item
    create_list(name: "Foods", items: "Pizza\nSushi", axes: %w[Taste])
    list = RankKing::DB[:lists].first
    item = RankKing::DB[:items].first(list_id: list[:id])
    axis = RankKing::DB[:axes].first(list_id: list[:id])

    csrf_post "/lists/#{list[:id]}/results", {
      axis_id: axis[:id],
      winner_id: item[:id],
      loser_id: item[:id],
    }, from: "/lists/#{list[:id]}/axes/#{axis[:id]}/compare"
    assert_equal 422, last_response.status
  end

  def test_root_links_to_list
    create_list(name: "Foods", items: "Pizza\nSushi")
    list = RankKing::DB[:lists].first

    get "/"
    assert_includes last_response.body, "/lists/#{list[:id]}"
    assert_includes last_response.body, "Foods"
  end

  def test_csrf_rejects_post_without_token
    post "/lists", { name: "Nope", items: "A\nB" }
    assert_equal 403, last_response.status
  end

  def test_create_list_adds_a_text_source
    create_list(name: "Foods", items: "Pizza\nSushi")
    list = RankKing::List.first

    assert_equal "Text", list.source_kind
    assert_equal %w[Pizza Sushi], list.items.map(&:name)
  end

  def test_text_sync_dialog_lists_items_for_editing
    create_list(name: "Foods", items: "Pizza\nSushi")
    list = RankKing::List.first
    pizza = list.items.find { |i| i.name == "Pizza" }

    get "/lists/#{list.id}"
    assert_includes last_response.body, "Edit items"
    assert_includes last_response.body, %(action="/lists/#{list.id}/sync")
    assert_includes last_response.body, %(name="items[#{pizza.id}]" value="Pizza")
  end

  def test_text_sync_renames_archives_and_adds_by_id
    create_list(name: "Foods", items: "Pizza\nSushi\nTacos", axes: %w[Taste])
    list = RankKing::List.first
    pizza, sushi, tacos = list.items_dataset.order(:id).all

    sync(list, {
      "items" => { pizza.id.to_s => "Pizza Margherita", sushi.id.to_s => "  ", tacos.id.to_s => "Tacos" },
      "new_items" => "Ramen\n\nCurry\n",
    })
    assert last_response.redirect?

    assert_equal "Pizza Margherita", pizza.reload.name
    refute_nil sushi.reload.archived_at
    assert_nil tacos.reload.archived_at
    assert_equal ["Pizza Margherita", "Tacos", "Ramen", "Curry"], list.items_dataset.order(:id).map(:name)

    get "/lists/#{list.id}"
    refute_includes last_response.body, "Sushi"
  end

  def test_text_sync_leaves_items_it_was_not_sent
    create_list(name: "Foods", items: "Pizza\nSushi")
    list = RankKing::List.first

    sync(list, { "new_items" => "Tacos" })
    assert_equal %w[Pizza Sushi Tacos], list.items_dataset.order(:id).map(:name)
  end

  def test_record_result_rejects_archived_item
    list, axis = create_list_with_axis(items: "Pizza\nSushi\nTacos")
    sushi = list.items.find { |i| i.name == "Sushi" }
    sushi.update(archived_at: Time.now)

    record_result(list, axis, winner: sushi, loser: list.items.first)
    assert_equal 422, last_response.status
  end

  def test_delete_list_with_archived_items
    list, = create_list_with_axis(items: "Pizza\nSushi\nTacos")
    list.items.first.update(archived_at: Time.now)

    csrf_post "/lists/#{list.id}/delete", {}, from: "/lists/#{list.id}/settings"
    assert_equal 0, RankKing::DB[:items].count
  end

  def test_lists_belong_to_the_current_user
    create_list(name: "Foods", items: "Pizza\nSushi")

    assert_equal LOGIN, RankKing::List.first.user.login
  end

  def test_requires_login
    header "Remote-User", nil
    get "/"
    assert_equal 401, last_response.status
  end

  def test_lists_are_private
    as("alice@example.com") { create_list(name: "Alpaca", items: "A\nB") }
    assert_equal 1, RankKing::List.count
    list = RankKing::List.first

    as("bob@example.com") do
      get "/"
      refute_includes last_response.body, "Alpaca"

      get "/lists/#{list.id}"
      assert_equal 404, last_response.status
    end
  end

  def test_new_list_form
    get "/lists/new"
    assert last_response.ok?
    assert_includes last_response.body, %(<option value="Text">Manual</option>)
    assert_includes last_response.body, "Create list"
  end

  def test_create_list_rejects_unknown_source
    post "/lists", { name: "Games", source: "bgg", items: "A\nB", _csrf: csrf_token_for("/lists", from: "/lists/new") }
    assert_equal 422, last_response.status
  end

  def test_show_list_ranks_items_on_each_axis
    list, axis = create_list_with_axis(items: "Pizza\nSushi\nTacos")
    pizza, sushi, = list.items
    record_result(list, axis, winner: sushi, loser: pizza)

    get "/lists/#{list.id}"
    body = last_response.body[/role="tabpanel".*/m]
    assert_operator body.index("Sushi"), :<, body.index("Pizza")
    assert_operator body.index("Pizza"), :<, body.index("Tacos")
    assert_includes body, %(<span class="gl-visually-hidden">, Unranked</span>)
    assert_includes body, "Compare on Taste"
  end

  def test_show_list_shows_ratings_on_ranked_rows_only
    list, axis = create_list_with_axis(items: "Pizza\nSushi\nTacos")
    pizza, sushi, = list.items
    record_result(list, axis, winner: sushi, loser: pizza)

    get "/lists/#{list.id}"
    body = last_response.body[/role="tabpanel".*/m]
    assert_equal 2, body.scan(/<span[^>]*data-rating/).size
    model = RankKing::CONFIG.open_skill
    winner, loser = [sushi, pizza].map { |i| axis.ratings.fetch(i.id) }
    assert_operator model.ordinal(loser), :<, 0
    shown = body.scan(%r{<span[^>]*data-rating[^>]*title="([^"]*)"[^>]*>(-?\d+\.\d)</span>})
    assert_equal [
      [format("μ %.1f σ %.1f", winner.mu, winner.sigma), format("%.1f", model.ordinal(winner))],
      [format("μ %.1f σ %.1f", loser.mu, loser.sigma), format("%.1f", model.ordinal(loser))]
    ], shown
  end

  def test_ranking_orders_by_rating_not_win_count
    list, axis = create_list_with_axis(items: "A\nB\nC")
    a, b, c = list.items.sort_by(&:id)
    record_result(list, axis, winner: a, loser: b)
    record_result(list, axis, winner: c, loser: a)

    ranked, unranked = axis.ranking
    assert_equal [c, a, b].map(&:id), ranked.map(&:id)
    assert_empty unranked
    assert_operator axis.ratings.fetch(c.id).mu, :>, axis.ratings.fetch(a.id).mu
  end

  def test_show_list_folds_everything_past_ten_into_a_disclosure
    list, axis = create_list_with_axis(items: (1..12).map { |n| "Item#{n}" }.join("\n"))
    record_result(list, axis, winner: list.items.first, loser: list.items.last)

    get "/lists/#{list.id}"
    body = last_response.body[/role="tabpanel".*/m]
    assert_includes body, "<summary>Show 2 more</summary>"
    assert_includes body, '<ol class="card" start="11">'
    visible, hidden = body.split("<details>")
    assert_equal 10, visible.scan("<li>").size
    assert_equal 2, hidden.scan("<li>").size
    assert_includes hidden, "—"
  end

  def test_show_list_folds_a_single_extra_item
    list, = create_list_with_axis(items: (1..11).map { |n| "Item#{n}" }.join("\n"))

    get "/lists/#{list.id}"
    assert_includes last_response.body, "<summary>Show 1 more</summary>"
  end

  def test_show_list_has_no_disclosure_for_ten_or_fewer
    list, = create_list_with_axis(items: (1..10).map { |n| "Item#{n}" }.join("\n"))

    get "/lists/#{list.id}"
    refute_includes last_response.body, "<details>"
  end

  def test_record_tie
    list, axis = create_list_with_axis(items: "Pizza\nSushi")
    pizza, sushi = list.items
    record_result(list, axis, winner: pizza, loser: sushi, tie: true)
    assert_equal "/lists/#{list.id}/axes/#{axis.id}/compare", URI(last_response.location).path

    result = axis.results_dataset.first
    assert result.tie
    assert_equal [pizza.id, sushi.id], [result.winner_id, result.loser_id]
  end

  def test_record_result_is_not_a_tie_by_default
    list, axis = create_list_with_axis(items: "Pizza\nSushi")
    record_result(list, axis, winner: list.items[0], loser: list.items[1])

    refute axis.results_dataset.first.tie
  end

  def test_record_tie_rejects_same_item
    list, axis = create_list_with_axis(items: "Pizza\nSushi")
    record_result(list, axis, winner: list.items[0], loser: list.items[0], tie: true)

    assert_equal 422, last_response.status
    assert_equal 0, RankKing::DB[:results].count
  end

  def test_record_result_rejects_an_unknown_tie_value
    list, axis = create_list_with_axis(items: "Pizza\nSushi")
    csrf_post "/lists/#{list.id}/results",
              { axis_id: axis.id, winner_id: list.items[0].id, loser_id: list.items[1].id, tie: "yes" },
              from: "/lists/#{list.id}/axes/#{axis.id}/compare"

    assert_equal 422, last_response.status
    assert_equal 0, RankKing::DB[:results].count
  end

  def test_record_tie_rejects_archived_item
    list, axis = create_list_with_axis(items: "Pizza\nSushi\nTacos")
    sushi = list.items.find { |i| i.name == "Sushi" }
    sushi.update(archived_at: Time.now)

    record_result(list, axis, winner: list.items.first, loser: sushi, tie: true)
    assert_equal 422, last_response.status
  end

  def test_compare_offers_a_tie_beside_skip
    list, axis = create_list_with_axis(items: "Pizza\nSushi")

    get "/lists/#{list.id}/axes/#{axis.id}/compare"
    actions = last_response.body[%r{<div data-matchup-actions>.*?</div>}m]
    refute_nil actions
    assert_includes actions, %(<input type="hidden" name="tie" value="1">)
    pair = actions.scan(/name="(?:winner|loser)_id" value="(\d+)"/).flatten.map(&:to_i)
    assert_equal list.items.map(&:id).sort, pair.sort
    first, second = pair.map { |id| list.items.find { |i| i.id == id }.name }
    assert_includes actions, %(<button type="submit" data-variant="ghost" aria-label="Tie: #{first} and #{second}">Tie</button>)
    assert_operator actions.index(">Tie</button>"), :<, actions.index(">Skip</a>")
  end

  def test_recent_shows_wins_and_ties
    list, axis = create_list_with_axis(items: "Pizza\nSushi")
    pizza = list.items.find { |i| i.name == "Pizza" }
    sushi = list.items.find { |i| i.name == "Sushi" }
    record_result(list, axis, winner: pizza, loser: sushi)
    record_result(list, axis, winner: sushi, loser: pizza, tie: true)

    get "/lists/#{list.id}/axes/#{axis.id}/compare"
    recent = last_response.body[/Recent.*/m]
    tie = recent.index("<span><strong>Sushi</strong> tied <strong>Pizza</strong></span>")
    win = recent.index("<span><strong>Pizza</strong> over Sushi</span>")
    refute_nil tie
    refute_nil win
    assert_operator tie, :<, win
  end

  def test_first_tie_leaves_both_items_level
    list, axis = create_list_with_axis(items: "Pizza\nSushi\nTacos")
    pizza, sushi, = list.items
    record_result(list, axis, winner: pizza, loser: sushi, tie: true)

    ratings = axis.ratings
    initial = OpenSkill::Model.new.rating
    assert_in_delta initial.mu, ratings.fetch(pizza.id).mu
    assert_in_delta initial.mu, ratings.fetch(sushi.id).mu
    assert_operator ratings.fetch(pizza.id).sigma, :<, initial.sigma
    _, unranked = axis.ranking(ratings)
    assert_equal ["Tacos"], unranked.map(&:name)
  end

  def test_tie_pulls_ratings_toward_each_other
    list, axis = create_list_with_axis(items: "A\nB")
    a, b = list.items.sort_by(&:id)
    record_result(list, axis, winner: a, loser: b)
    before = axis.ratings

    record_result(list, axis, winner: b, loser: a, tie: true)
    after = axis.ratings

    assert_operator after.fetch(a.id).mu, :<, before.fetch(a.id).mu
    assert_operator after.fetch(b.id).mu, :>, before.fetch(b.id).mu
    assert_operator after.fetch(a.id).mu, :>, after.fetch(b.id).mu
    assert_equal [a, b].map(&:id), axis.ranking(after).first.map(&:id)
  end

  def test_show_list_selects_the_requested_axis
    create_list(name: "Foods", items: "Pizza\nSushi", axes: %w[Taste Value])
    list = RankKing::List.first
    value = list.axes.last

    get "/lists/#{list.id}?axis=#{value.id}"
    assert_match(/id="axis-#{value.id}-tab"[^>]*aria-selected="true"/, last_response.body)
  end

  def test_show_list_without_axes_offers_the_first
    create_list(name: "Simple", items: "A\nB")
    list = RankKing::List.first

    get "/lists/#{list.id}"
    assert_includes last_response.body, %(action="/lists/#{list.id}/axes")
    assert_includes last_response.body, 'aria-label="New axis"'
  end

  def test_add_axis_from_the_list
    create_list(name: "Simple", items: "A\nB")
    list = RankKing::List.first

    csrf_post "/lists/#{list.id}/axes", { name: " Taste " }, from: "/lists/#{list.id}"
    axis = list.axes_dataset.first
    assert_equal "Taste", axis.name
    assert_equal "/lists/#{list.id}", URI(last_response.location).path
    assert_equal "axis=#{axis.id}", URI(last_response.location).query

    follow_redirect!
    assert_includes last_response.body, "Compare on Taste"
  end

  def test_add_axis_rejects_empty_name
    create_list(name: "Simple", items: "A\nB")
    list = RankKing::List.first

    csrf_post "/lists/#{list.id}/axes", { name: " " }, from: "/lists/#{list.id}"
    assert_equal 422, last_response.status
  end

  def test_compare_shows_a_pair
    list, axis = create_list_with_axis(items: "Pizza\nSushi")

    get "/lists/#{list.id}/axes/#{axis.id}/compare"
    assert last_response.ok?
    assert_includes last_response.body, "Which wins on Taste?"
    assert_includes last_response.body, "Pizza"
    assert_includes last_response.body, "Sushi"
  end

  def test_text_items_show_as_their_names
    list, axis = create_list_with_axis(items: "Pizza\nSushi")

    get "/lists/#{list.id}"
    assert_includes last_response.body, %(<span class="type-label">—</span>Pizza<span class="gl-visually-hidden">, Unranked</span>)
    refute_includes last_response.body, "data-video"

    get "/lists/#{list.id}/axes/#{axis.id}/compare"
    assert_includes last_response.body, %(<button type="submit">Pizza</button>)
    assert_includes last_response.body, %(<button type="submit">Sushi</button>)
  end

  def test_compare_404_for_an_axis_on_another_list
    _, axis = create_list_with_axis(items: "Pizza\nSushi")
    other, = create_list_with_axis(items: "A\nB")

    get "/lists/#{other.id}/axes/#{axis.id}/compare"
    assert_equal 404, last_response.status
  end

  def test_record_result_returns_to_compare
    list, axis = create_list_with_axis(items: "Pizza\nSushi")
    record_result(list, axis, winner: list.items[0], loser: list.items[1])

    assert_equal "/lists/#{list.id}/axes/#{axis.id}/compare", URI(last_response.location).path

    follow_redirect!
    assert_includes last_response.body, "Recent"
  end

  def test_settings_shows_the_fixed_source
    list, = create_list_with_axis(items: "Pizza\nSushi")

    get "/lists/#{list.id}/settings"
    assert last_response.ok?
    assert_includes last_response.body, "<p>Manual</p>"
    refute_includes last_response.body, '<select name="source"'
  end

  def test_settings_renames_and_edits_axes
    create_list(name: "Foods", items: "Pizza\nSushi", axes: %w[Taste Value])
    list = RankKing::List.first
    taste, value = list.axes
    record_result(list, value, winner: list.items[0], loser: list.items[1])

    update_settings(list, name: "Meals", axis_ids: [taste.id], axes: ["Price", ""])
    assert last_response.redirect?

    list.reload
    assert_equal "Meals", list.name
    assert_equal %w[Taste Price], list.axes.map(&:name)
    assert_equal 0, RankKing::DB[:results].count
  end

  def test_settings_rejects_empty_name
    list, = create_list_with_axis(items: "Pizza\nSushi")
    update_settings(list, name: " ")
    assert_equal 422, last_response.status
  end

  def test_delete_list
    list, axis = create_list_with_axis(items: "Pizza\nSushi")
    record_result(list, axis, winner: list.items[0], loser: list.items[1])

    csrf_post "/lists/#{list.id}/delete", {}, from: "/lists/#{list.id}/settings"
    assert last_response.redirect?

    %i[lists items axes results].each { |table| assert_equal 0, RankKing::DB[table].count, table }
  end

  def test_settings_are_private
    list = as("alice@example.com") { create_list_with_axis(items: "A\nB").first }

    get "/lists/#{list.id}/settings"
    assert_equal 404, last_response.status
  end

  private

  def create_list_with_axis(items:)
    create_list(name: "Foods", items: items, axes: %w[Taste])
    list = RankKing::List.order(:id).last
    [list, list.axes.first]
  end

  def record_result(list, axis, winner:, loser:, tie: false)
    params = { axis_id: axis.id, winner_id: winner.id, loser_id: loser.id }
    params[:tie] = "1" if tie
    csrf_post "/lists/#{list.id}/results", params,
              from: "/lists/#{list.id}/axes/#{axis.id}/compare"
  end

  def sync(list, params)
    csrf_post "/lists/#{list.id}/sync", params, from: "/lists/#{list.id}"
  end

  def update_settings(list, name:, axis_ids: list.axes.map(&:id), axes: [])
    csrf_post "/lists/#{list.id}/settings", { name: name, axis_ids: axis_ids, axes: axes },
              from: "/lists/#{list.id}/settings"
  end

  def csrf_token_for(path, from:)
    get from
    last_response.body[/action="#{Regexp.escape(path)}".*?name="_csrf" value="([^"]+)"/m, 1]
  end

  def as(login)
    header "Remote-User", login
    yield
  ensure
    header "Remote-User", LOGIN
  end

  # Posts with the CSRF token of the form on page `from` that targets `path`.
  def csrf_post(path, params = {}, from:)
    post path, params.merge("_csrf" => csrf_token_for(path, from: from))
  end

  def create_list(name:, items:, axes: [])
    csrf_post "/lists", { name: name, source: "Text", items: items, axes: axes }, from: "/lists/new"
  end
end