test_data.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import datetime
  2. import uuid
  3. import random
  4. import string
  5. from .models import TransactionEvent, TransactionGroup, Span
  6. TRANSACTIONS = [
  7. "generic WSGI request",
  8. "/admin",
  9. "/admin/login/",
  10. "/",
  11. "/favicon.ico",
  12. "/foo",
  13. "/bar",
  14. ]
  15. OPS = [
  16. "http.server",
  17. "pageload",
  18. "http",
  19. "browser",
  20. "db",
  21. "django.middleware",
  22. "django.view",
  23. "django.foo",
  24. "django.bar",
  25. ]
  26. METHODS = [
  27. "GET",
  28. "POST",
  29. "PATCH",
  30. "PUT",
  31. "DELETE",
  32. ]
  33. def maybe_random_string():
  34. if random.getrandbits(6) == 0: # small chance
  35. return "".join(random.choices(string.ascii_uppercase + string.digits, k=20))
  36. def generate_random_transaction():
  37. return maybe_random_string() or random.choice(TRANSACTIONS)
  38. def generate_random_op():
  39. randbits = random.getrandbits(3)
  40. if randbits == 0: # Favor http.server
  41. return "http.server"
  42. return maybe_random_string() or random.choice(OPS)
  43. def generate_random_method():
  44. return random.choice(METHODS)
  45. def generate_random_timestamp(start_timestamp):
  46. """
  47. Generate a realistic looking random time interval
  48. small chance between 0 and 30 seconds
  49. most will be between 0 and 2 seconds
  50. """
  51. if random.getrandbits(3) == 0:
  52. interval = random.randint(0, 30000)
  53. else:
  54. interval = random.randint(0, 2000)
  55. return start_timestamp + datetime.timedelta(milliseconds=interval)
  56. def generate_fake_transaction_event(project, start_timestamp):
  57. """
  58. Generate random transaction and return result (unsaved)
  59. Will get_or_create the transaction group, function will result in queries
  60. """
  61. op = generate_random_op()
  62. method = None
  63. if op == "http.server":
  64. method = generate_random_method()
  65. group, _ = TransactionGroup.objects.get_or_create(
  66. transaction=generate_random_transaction(),
  67. project=project,
  68. op=op,
  69. method=method,
  70. )
  71. timestamp=generate_random_timestamp(start_timestamp)
  72. return TransactionEvent(
  73. group=group,
  74. trace_id=uuid.uuid4(),
  75. start_timestamp=start_timestamp,
  76. data={},
  77. timestamp=timestamp,
  78. duration=timestamp - start_timestamp
  79. )