~singpolyma/jmp-pay

7958c1c5bb43796c0d02663965eee8c89112b812 — Stephen Paul Weber 8 months ago f84f822
Factor out AutoTopUpRepo and add tests
3 files changed, 86 insertions(+), 7 deletions(-)

M config.ru
A lib/auto_top_up_repo.rb
A test/test_auto_top_up_repo.rb
M config.ru => config.ru +6 -7
@@ 193,7 193,7 @@ class JmpPay < Roda
			Sentry.set_user(id: params["customer_id"], jid: jid)

			gateway = CreditCardGateway.new(jid, params["customer_id"])
			topup = "jmp_customer_auto_top_up_amount-#{gateway.customer_id}"
			topup = AutoTopUpRepo.new

			r.on "credit_cards" do
				r.get do


@@ 202,7 202,7 @@ class JmpPay < Roda
						locals: {
							token: gateway.client_token,
							customer_id: gateway.customer_id,
							auto_top_up: REDIS.get(topup) ||
							auto_top_up: topup.find(gateway.customer_id) ||
							             (gateway.payment_methods? ? "" : "15")
						}
					)


@@ 210,11 210,10 @@ class JmpPay < Roda

				r.post do
					gateway.default_payment_method = params["braintree_nonce"]
					if params["auto_top_up_amount"].to_i >= 15
						REDIS.set(topup, params["auto_top_up_amount"].to_i)
					elsif params["auto_top_up_amount"].to_i.zero?
						REDIS.del(topup)
					end
					topup.put(
						gateway.customer_id,
						params["auto_top_up_amount"].to_i
					)
					"OK"
				end
			end

A lib/auto_top_up_repo.rb => lib/auto_top_up_repo.rb +30 -0
@@ 0,0 1,30 @@
# frozen_string_literal: true

class AutoTopUpRepo
	def initialize(redis: REDIS, db: DB)
		@redis = redis
		@db = db
	end

	def find(customer_id)
		redis(:get, customer_id)
	end

	def put(customer_id, amount)
		if amount >= 15
			redis(:set, customer_id, amount)
		elsif amount.zero?
			redis(:del, customer_id)
		end
	end

protected

	def redis(action, customer_id, *args)
		@redis.public_send(
			action,
			"jmp_customer_auto_top_up_amount-#{customer_id}",
			*args
		)
	end
end

A test/test_auto_top_up_repo.rb => test/test_auto_top_up_repo.rb +50 -0
@@ 0,0 1,50 @@
# frozen_string_literal: true

require "test_helper"
require "auto_top_up_repo"

class AutoTopUpRepoTest < Minitest::Test
	def setup
		@redis = Minitest::Mock.new
		@db = Minitest::Mock.new
		@repo = AutoTopUpRepo.new(redis: @redis, db: @db)
	end

	property(:find) { string }
	def find(customer_id)
		@redis.expect(
			:get,
			nil,
			["jmp_customer_auto_top_up_amount-#{customer_id}"]
		)
		@repo.find(customer_id)
		assert_mock @redis
	end

	property(:put_valid_amount) { range(15, 9999999) }
	def put_valid_amount(amount)
		@redis.expect(
			:set,
			nil,
			["jmp_customer_auto_top_up_amount-somecustomer", amount]
		)
		@repo.put("somecustomer", amount)
		assert_mock @redis
	end

	property(:put_invalid_amount) { branch [:range, 1, 14], [:range, -999, -1] }
	def put_invalid_amount(amount)
		@repo.put("somecustomer", amount)
		assert_mock @redis
	end

	def test_put_zero
		@redis.expect(
			:del,
			nil,
			["jmp_customer_auto_top_up_amount-somecustomer"]
		)
		@repo.put("somecustomer", 0)
		assert_mock @redis
	end
end