Add initial trades tests

This commit is contained in:
badblocks 2025-03-27 00:16:44 -07:00
parent d66ed823e0
commit 2785e0ed13
2 changed files with 477 additions and 12 deletions

View file

@ -230,14 +230,16 @@ class TradeOfferDeleteView(LoginRequiredMixin, DeleteView):
template_name = "trades/trade_offer_delete.html"
def dispatch(self, request, *args, **kwargs):
trade_offer = self.get_object()
if trade_offer.initiated_by_id not in request.user.friend_codes.values_list("id", flat=True):
# Retrieve the object normally
self.object = super().get_object()
# Perform the permission check here
if self.object.initiated_by_id not in request.user.friend_codes.values_list("id", flat=True):
raise PermissionDenied("You are not authorized to delete or close this trade offer.")
return super().dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
trade_offer = self.get_object()
trade_offer = self.object
terminal_states = [
TradeAcceptance.AcceptanceState.THANKED_BY_INITIATOR,
TradeAcceptance.AcceptanceState.THANKED_BY_ACCEPTOR,
@ -255,7 +257,7 @@ class TradeOfferDeleteView(LoginRequiredMixin, DeleteView):
return context
def post(self, request, *args, **kwargs):
trade_offer = self.get_object()
trade_offer = self.object
terminal_states = [
TradeAcceptance.AcceptanceState.THANKED_BY_INITIATOR,
TradeAcceptance.AcceptanceState.THANKED_BY_ACCEPTOR,
@ -265,8 +267,11 @@ class TradeOfferDeleteView(LoginRequiredMixin, DeleteView):
]
active_acceptances = trade_offer.acceptances.exclude(state__in=terminal_states)
if active_acceptances.exists():
messages.error(request, "Cannot delete or close this trade offer because there are active acceptances.")
context = self.get_context_data(object=trade_offer)
messages.error(
request,
"Cannot close this trade offer while there are active acceptances. Please reject all acceptances before closing, or finish the trades."
)
context = self.get_context_data()
return self.render_to_response(context)
else:
if trade_offer.acceptances.count() > 0:
@ -583,13 +588,14 @@ class TradeAcceptanceUpdateView(LoginRequiredMixin, UpdateView):
def form_valid(self, form):
new_state = form.cleaned_data["state"]
#match the new state to the TradeAcceptance.AcceptanceState enum
if new_state not in TradeAcceptance.AcceptanceState:
try:
# Try to cast new_state to the enum member
valid_state = TradeAcceptance.AcceptanceState(new_state)
except ValueError:
form.add_error("state", "Invalid state transition.")
return self.form_invalid(form)
try:
# pass the new state and the current user to the update_state method
form.instance.update_state(new_state, self.request.user)
form.instance.update_state(valid_state, self.request.user)
except ValueError as e:
form.add_error("state", str(e))
return self.form_invalid(form)