test_data.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. return TransactionEvent(
  72. group=group,
  73. trace_id=uuid.uuid4(),
  74. start_timestamp=start_timestamp,
  75. data={},
  76. timestamp=generate_random_timestamp(start_timestamp),
  77. )