test_data.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import datetime
  2. import random
  3. import string
  4. import uuid
  5. from .models import TransactionEvent, TransactionGroup
  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. RELEASES = [
  34. None,
  35. "1.0",
  36. "1.1",
  37. "1.2",
  38. "1.3",
  39. "2.0",
  40. "2.1",
  41. ]
  42. ENVIRONMENTS = [None, "local", "dev", "staging", "production"]
  43. def maybe_random_string():
  44. if random.getrandbits(6) == 0: # small chance
  45. return "".join(random.choices(string.ascii_uppercase + string.digits, k=20))
  46. def generate_random_transaction():
  47. return maybe_random_string() or random.choice(TRANSACTIONS)
  48. def generate_random_op():
  49. randbits = random.getrandbits(3)
  50. if randbits == 0: # Favor http.server
  51. return "http.server"
  52. return maybe_random_string() or random.choice(OPS)
  53. def generate_random_method():
  54. return random.choice(METHODS)
  55. def generate_random_timestamp(start_timestamp):
  56. """
  57. Generate a realistic looking random time interval
  58. small chance between 0 and 30 seconds
  59. most will be between 0 and 2 seconds
  60. """
  61. if random.getrandbits(3) == 0:
  62. interval = random.randint(0, 30000)
  63. else:
  64. interval = random.randint(0, 2000)
  65. return start_timestamp + datetime.timedelta(milliseconds=interval)
  66. def generate_fake_transaction_event(project, start_timestamp):
  67. """
  68. Generate random transaction and return result (unsaved)
  69. Will get_or_create the transaction group, function will result in queries
  70. """
  71. op = generate_random_op()
  72. method = None
  73. if op == "http.server":
  74. method = generate_random_method()
  75. group, _ = TransactionGroup.objects.get_or_create(
  76. transaction=generate_random_transaction(),
  77. project=project,
  78. op=op,
  79. method=method,
  80. )
  81. timestamp = generate_random_timestamp(start_timestamp)
  82. tags = {}
  83. if release := random.choice(RELEASES):
  84. tags["release"] = release
  85. if environment := random.choice(ENVIRONMENTS):
  86. tags["environment"] = environment
  87. return TransactionEvent(
  88. group=group,
  89. trace_id=uuid.uuid4(),
  90. start_timestamp=start_timestamp,
  91. data={},
  92. timestamp=timestamp,
  93. duration=timestamp - start_timestamp,
  94. tags=tags,
  95. )