test_data.py 2.4 KB

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