示例#1
0
class TestPtBR(unittest.TestCase):

    def setUp(self):
        self.factory = Faker('pt_BR')
        self.provider = self.factory.provider('faker.providers.internet')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'VitóriaMagalhães',
    )
    def test_ascii_safe_email(self):
        email = self.factory.ascii_safe_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'vitoriamagalhaes'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'JoãoSimões',
    )
    def test_ascii_free_email(self):
        email = self.factory.ascii_free_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'joaosimoes'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'AndréCauã',
    )
    def test_ascii_company_email(self):
        email = self.factory.ascii_company_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'andrecaua'
示例#2
0
class TestPtBR(unittest.TestCase):
    def setUp(self):
        self.factory = Faker('pt_BR')
        self.provider = self.factory.provider('faker.providers.internet')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'VitóriaMagalhães',
    )
    def test_ascii_safe_email(self):
        email = self.factory.ascii_safe_email()
        validate_email(email)
        assert email.split('@')[0] == 'vitoriamagalhaes'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'JoãoSimões',
    )
    def test_ascii_free_email(self):
        email = self.factory.ascii_free_email()
        validate_email(email)
        assert email.split('@')[0] == 'joaosimoes'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'AndréCauã',
    )
    def test_ascii_company_email(self):
        email = self.factory.ascii_company_email()
        validate_email(email)
        assert email.split('@')[0] == 'andrecaua'
示例#3
0
class TestArAa(unittest.TestCase):

    def setUp(self):
        self.factory = Faker('ar_AA')
        self.provider = self.factory.provider('faker.providers.internet')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'اصيل',
    )
    def test_ascii_safe_email(self):
        email = self.factory.ascii_safe_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'asyl'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'اصيل',
    )
    def test_ascii_free_email(self):
        email = self.factory.ascii_free_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'asyl'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'اصيل',
    )
    def test_ascii_company_email(self):
        email = self.factory.ascii_company_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'asyl'
示例#4
0
class TestNlNl(unittest.TestCase):
    def setUp(self):
        self.factory = Faker('nl_NL')
        self.provider = self.factory.provider('faker.providers.internet')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'fabiënné',
    )
    def test_ascii_safe_email(self):
        email = self.factory.ascii_safe_email()
        validate_email(email)
        assert email.split('@')[0] == 'fabienne'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'fabiënné',
    )
    def test_ascii_free_email(self):
        email = self.factory.ascii_free_email()
        validate_email(email)
        assert email.split('@')[0] == 'fabienne'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'fabiënné',
    )
    def test_ascii_company_email(self):
        email = self.factory.ascii_company_email()
        validate_email(email)
        assert email.split('@')[0] == 'fabienne'
示例#5
0
class TestArAa(unittest.TestCase):
    def setUp(self):
        self.factory = Faker('ar_AA')
        self.provider = self.factory.provider('faker.providers.internet')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'اصيل',
    )
    def test_ascii_safe_email(self):
        email = self.factory.ascii_safe_email()
        validate_email(email)
        assert email.split('@')[0] == 'asyl'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'اصيل',
    )
    def test_ascii_free_email(self):
        email = self.factory.ascii_free_email()
        validate_email(email)
        assert email.split('@')[0] == 'asyl'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'اصيل',
    )
    def test_ascii_company_email(self):
        email = self.factory.ascii_company_email()
        validate_email(email)
        assert email.split('@')[0] == 'asyl'
class TestWework:
    def setup_class(self):
        corpid = "XXXXXXXXXXXXXXXXXXXXXXXXX"
        contact_corpsecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
        self.fake = Faker(locale='zh_CN')
        self.wework = User_API()
        self.wework.get_access_token(corpid,contact_corpsecret)
        self.department = department_API()
        self.department.get_access_token(corpid,contact_corpsecret)


    def test_Adduesr(self):
        userid = self.fake.user_name()
        name = self.fake.name()
        mobile = "+86 "+ self.fake.phone_number()
        department =[self.department.get_department().json()['department'][-1]['id']]
        email = self.fake.ascii_company_email()
        print(f"userid:{userid},name:{name},mobile:{mobile},department:{department},email:{email}")
        e = self.wework.create_User(userid,name,mobile,department=[4],email=email)
        print(e.json())
        assert e.json()["errcode"] == 0


    def test_delUser(self):
        print(self.department.get_department().json())
        userid = self.department.get_department_uesr().json()["userlist"][0]["userid"]
        print(userid)
        a = self.wework.del_User(userid)
        assert a.json()["errcode"] == 0
        assert userid not in json.dumps(self.department.get_department_uesr().json(), indent=2, ensure_ascii=False)
示例#7
0
class TestNlNl(unittest.TestCase):

    def setUp(self):
        self.factory = Faker('nl_NL')
        self.provider = self.factory.provider('faker.providers.internet')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'fabiënné'
    )
    def test_ascii_safe_email(self):
        email = self.factory.ascii_safe_email()
        validate_email(email, check_deliverability=False)
        self.assertEqual(email.split('@')[0], 'fabienne')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'fabiënné'
    )
    def test_ascii_free_email(self):
        email = self.factory.ascii_free_email()
        validate_email(email, check_deliverability=False)
        self.assertEqual(email.split('@')[0], 'fabienne')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'fabiënné'
    )
    def test_ascii_company_email(self):
        email = self.factory.ascii_company_email()
        validate_email(email, check_deliverability=False)
        self.assertEqual(email.split('@')[0], 'fabienne')
示例#8
0
文件: utils.py 项目: Ni88l3r/Hillel
def generate_users(quantity: int) -> str:
    fake = Faker(['en_US', 'ru_RU', 'uk_UA'])
    users = ''
    for _ in range(quantity):
        users = users + '<b>' + fake.first_name(
        ) + '</b> ' + fake.ascii_company_email() + '<br/>'
    return users
示例#9
0
    def handle(self, *args, **options):
        before_c_user = NewUser.objects.all().count()
        before_c_ins = Institution.objects.all().count()
        before_c_cat = Category.objects.all().count()
        before_c_don = Donation.objects.all().count()

        fake = Faker(['pl_PL'])
        for _ in range(15):
            x = fake.first_name()
            User.objects.create_user(first_name=x,
                                     password=x,
                                     email=fake.ascii_company_email())
        for _ in range(random.randint(10, 20)):
            cat = Category.objects.create(name=fake.word())
            cat.save()

        for _ in range(random.randint(5, 15)):
            ins = Institution.objects.create(
                name=fake.domain_name(),
                description=fake.text(max_nb_chars=80),
                type=random.randint(1, 3))
            ins.save()
            for _ in range(random.randint(3, 6)):
                cat = Category.objects.all().order_by('?')[0]
                ins.categories.add(cat)

        for _ in range(random.randint(80, 100)):
            user = NewUser.objects.all().order_by('?')[0]
            ins = Institution.objects.all().order_by('?')[0]
            cat = Category.objects.all().order_by('?')[0]
            d = Donation.objects.create(
                quantity=random.randint(1, 50),
                institution=ins,
                address=fake.street_address(),
                phone_number=random.randint(222222222, 999999999),
                city=fake.city(),
                zip_code=fake.postcode(),
                pick_up_date=fake.date(),
                pick_up_time=random.randint(0, 1449),
                pick_up_comment=fake.text(max_nb_chars=40),
                user=user)
            d.save()
            d.categories.add(cat)

        after_c_user = NewUser.objects.all().count()
        after_c_ins = Institution.objects.all().count()
        after_c_cat = Category.objects.all().count()
        after_c_don = Donation.objects.all().count()

        self.stdout.write(self.style.SUCCESS('Wypełnienie bazy pomyślne:'))
        self.stdout.write(
            self.style.SUCCESS(f'User: {before_c_user} -> {after_c_user}'))
        self.stdout.write(
            self.style.SUCCESS(
                f'Institution: {before_c_ins} -> {after_c_ins}'))
        self.stdout.write(
            self.style.SUCCESS(f'Category: {before_c_cat} -> {after_c_cat}'))
        self.stdout.write(
            self.style.SUCCESS(f'Donation: {before_c_don} -> {after_c_don}'))
print(fake.unix_partition())


print("providers.geo".center(100,"="))

print(fake.coordinate())
print(fake.latitude())
print(fake.latlng())
print(fake.local_latlng())
print(fake.location_on_land())
print(fake.longitude())


print("providers.internet".center(100,"="))

print(fake.ascii_company_email())
print(fake.ascii_email())
print(fake.ascii_free_email())
print(fake.ascii_safe_email())
print(fake.company_email())
print(fake.dga())
print(fake.domain_name())
print(fake.domain_word())
print(fake.email())
print(fake.free_email())
print(fake.free_email_domain())
print(fake.hostname())
print(fake.http_method())
print(fake.image_url())
print(fake.ipv4())
print(fake.ipv4_network_class())
示例#11
0
class TrackerTest(unittest.TestCase):
    def setUp(self):
        self.apiUrl = "http://localhost:3002/api"
        self.fake = Faker()
        self.setUserObject()
        self.customTimeline = {
            "category": "cart",
            "type": "info",
            "content": {
                "message": "test-content"
            }
        }
        try:
            # create user
            createdUser = self.apiRequest(self.apiUrl + "/user/signup",
                                          self.user, {})

            # get token and project
            token = createdUser["tokens"]["jwtAccessToken"]
            self.header = {"Authorization": "Basic " + token}
            self.project = createdUser["project"]

            # create a component
            component = {"name": self.fake.word()}
            createdComponent = self.apiRequest(
                self.apiUrl + "/component/" + self.project["_id"],
                component,
                self.header,
            )
            self.component = createdComponent

            # create an errorTracker and set it as the global error tracker.
            errorTracker = {"name": self.fake.word()}
            createdErrorTracker = self.apiRequest(
                self.apiUrl + "/error-tracker/" + self.project["_id"] + "/" +
                createdComponent["_id"] + "/create",
                errorTracker,
                self.header,
            )
            self.errorTracker = createdErrorTracker

        except requests.exceptions.HTTPError as error:
            print(
                "Couldnt create an error tracker to run a test, Error occured: "
            )
            print(error)

    def setUserObject(self):
        self.user = {
            "name": self.fake.name(),
            "password": "******",
            "confirmPassword": "******",
            "email": self.fake.ascii_company_email(),
            "companyName": self.fake.company(),
            "jobRole": self.fake.job(),
            "companySize": self.fake.random_int(),
            "card": {
                "stripeToken": "tok_visa"
            },
            "subscription": {
                "stripePlanId": 0
            },
            "cardName": self.fake.credit_card_provider(),
            "cardNumber": self.fake.credit_card_number(),
            "cvv": self.fake.credit_card_security_code(),
            "expiry": self.fake.credit_card_expire(),
            "city": self.fake.city(),
            "state": self.fake.country(),
            "zipCode": self.fake.postcode(),
            "companyRole": self.fake.job(),
            "companyPhoneNumber": self.fake.phone_number(),
            "planId": "plan_GoWIYiX2L8hwzx",
            "reference": "Github",
        }
        return self

    def apiRequest(self, url, body, headers):
        response = requests.post(url, body, headers=headers)
        return response.json()

    def test_should_take_in_custom_timeline_event(self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])
        timeline = tracker.getTimeline()
        self.assertIsInstance(timeline, list)
        self.assertEqual(1, len(timeline))
        self.assertEqual(self.customTimeline["category"],
                         timeline[0]["category"])

    def test_should_ensure_timeline_event_contains_eventId_and_timestamp(self):

        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])
        timeline = tracker.getTimeline()
        self.assertIsInstance(timeline[0]["eventId"], str)
        self.assertIsInstance(timeline[0]["timestamp"], str)

    def test_should_ensure_different_timeline_event_have_the_same_eventId(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"], "error")
        timeline = tracker.getTimeline()
        self.assertEqual(2, len(timeline))  # two timeline events
        self.assertEqual(
            timeline[0]["eventId"], timeline[1]["eventId"]
        )  # their eventId is the same, till there is an error sent to the server

    def test_should_ensure_max_timline_cant_be_set_as_a_negative_number(self):
        options = {"maxTimeline": -5}
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"], options)

        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"], "error")
        timeline = tracker.getTimeline()
        self.assertEqual(2, len(timeline))  # two timeline events

    def test_should_ensure_new_timeline_event_after_max_timeline_are_discarded(
            self):
        options = {"maxTimeline": 2}
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"], options)

        customTimeline2 = {
            "category": "logout",
            "type": "success",
            "content": {
                "message": "tester"
            }
        }

        # add 3 timeline events
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])
        tracker.addToTimeline(customTimeline2["category"],
                              customTimeline2["content"],
                              customTimeline2["type"])
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"], "debug")
        timeline = tracker.getTimeline()

        self.assertEqual(options["maxTimeline"],
                         len(timeline))  # three timeline events
        self.assertEqual(timeline[0]["type"], self.customTimeline["type"])
        self.assertEqual(timeline[1]["category"], customTimeline2["category"])

    def test_should_add_tags(self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        tag = {"key": "location", "value": "Warsaw"}
        tracker.setTag(tag['key'], tag['value'])

        availableTags = tracker.getTags()
        self.assertIsInstance(availableTags, list)
        self.assertEqual(1, len(availableTags))
        self.assertEqual(tag['key'], availableTags[0]['key'])

    def test_should_add_multiple_tags(self):

        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])
        tags = []
        tag = {"key": "location", "value": "Warsaw"}
        tags.append(tag)

        tagB = {"key": "city", "value": "Leeds"}
        tags.append(tagB)

        tagC = {"key": "device", "value": "iPhone"}
        tags.append(tagC)

        tracker.setTags(tags)

        availableTags = tracker.getTags()
        self.assertIsInstance(availableTags, list)
        self.assertEqual(len(tags), len(availableTags))

    def test_should_overwrite_existing_keys_to_avoid_duplicate_tags(self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        tags = []
        tag = {"key": "location", "value": "Warsaw"}
        tags.append(tag)

        tagB = {"key": "city", "value": "Leeds"}
        tags.append(tagB)

        tagC = {"key": "location", "value": "Paris"}
        tags.append(tagC)

        tagD = {"key": "device", "value": "iPhone"}
        tags.append(tagD)

        tagE = {"key": "location", "value": "London"}
        tags.append(tagE)

        tracker.setTags(tags)

        availableTags = tracker.getTags()
        self.assertIsInstance(availableTags, list)
        self.assertEqual(3, len(availableTags))  # only 3 unique tags
        self.assertEqual(tagC["key"], availableTags[0]["key"])
        self.assertNotEqual(
            tagC["value"],
            availableTags[0]["value"])  # old value for that tag location
        self.assertEqual(tagE["key"], availableTags[0]["key"])
        self.assertEqual(
            tagE["value"],
            availableTags[0]["value"])  # latest value for that tag location

    def test_should_create_fingerprint_as_message_for_error_capture_without_any_fingerprint(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        errorMessage = "Uncaught Exception"
        tracker.captureMessage(errorMessage)
        event = tracker.getCurrentEvent()
        self.assertEqual(event["fingerprint"][0], errorMessage)

    def test_should_use_defined_fingerprint_array_for_error_capture_with_fingerprint(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        fingerprints = ['custom', 'errors']
        tracker.setFingerPrint(fingerprints)
        errorMessage = 'Uncaught Exception'
        tracker.captureMessage(errorMessage)
        event = tracker.getCurrentEvent()
        self.assertEqual(event["fingerprint"][0], fingerprints[0])
        self.assertEqual(event["fingerprint"][1], fingerprints[1])

    def test_should_use_defined_fingerprint_string_for_error_capture_with_fingerprint(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        fingerprint = 'custom-fingerprint'
        tracker.setFingerPrint(fingerprint)
        errorMessage = 'Uncaught Exception'
        tracker.captureMessage(errorMessage)
        event = tracker.getCurrentEvent()
        self.assertEqual(event["fingerprint"][0], fingerprint)

    def test_should_create_an_event_ready_for_the_server_using_capture_message(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        errorMessage = 'This is a test'
        tracker.captureMessage(errorMessage)
        event = tracker.getCurrentEvent()
        self.assertEqual(event["type"], "message")
        self.assertEqual(event["exception"]["message"], errorMessage)

    def test_should_create_an_event_ready_for_the_server_while_having_the_timeline_with_same_event_id(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])

        errorMessage = 'This is a test'
        tracker.captureMessage(errorMessage)
        event = tracker.getCurrentEvent()

        self.assertEqual(2, len(event["timeline"]))
        self.assertEqual(event["eventId"], event["timeline"][0]["eventId"])
        self.assertEqual(event["exception"]["message"], errorMessage)

    def test_should_create_an_event_ready_for_the_server_using_capture_exception(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        errorMessage = 'Error Found'
        tracker.captureException(Exception(errorMessage))
        event = tracker.getCurrentEvent()
        self.assertEqual(event["type"], 'exception')
        self.assertEqual(event["exception"]["message"], errorMessage)

    def test_should_create_an_event_with_array_of_stacktrace(self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        errorType = 'ZeroDivisionError'
        try:
            divByZero = 1 / 0
        except Exception as ex:
            tracker.captureException(ex)
        event = tracker.getCurrentEvent()
        self.assertEqual(event["type"], 'exception')
        self.assertEqual(event["exception"]["type"], errorType)
        self.assertIsInstance(event["exception"]["stacktrace"], dict)
        self.assertIsInstance(event["exception"]["stacktrace"]["frames"], list)

    def test_should_create_an_event_with_the_object_of_the_stacktrace_in_place(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        errorType = 'ZeroDivisionError'
        try:
            divByZero = 1 / 0
        except Exception as ex:
            tracker.captureException(ex)
        event = tracker.getCurrentEvent()
        frame = event["exception"]["stacktrace"]["frames"][0]

        self.assertIn("methodName", frame)
        self.assertIn("lineNumber", frame)
        self.assertIn("fileName", frame)

    def test_should_create_an_event_and_new_event_should_have_different_id(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])
        errorMessage = 'division by zero'
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])
        event = tracker.captureMessage(errorMessage)
        # event = tracker.getCurrentEvent()

        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])

        newEvent = None
        errorType = 'division by zero'
        try:
            divByZero = 1 / 0
        except Exception as ex:
            newEvent = tracker.captureException(ex)
            # newEvent = tracker.getCurrentEvent()
        # ensure that the first event have a type message, same error message
        self.assertEqual(event["type"], 'message')
        self.assertEqual(event["content"]["message"], errorMessage)

        # ensure that the second event have a type exception, same error message
        self.assertEqual(newEvent["type"], 'exception')
        self.assertEqual(newEvent["content"]["message"], errorMessage)

        # confim their eventId is different
        self.assertNotEqual(event["_id"], newEvent["_id"])

    def test_should_create_an_event_that_has_timeline_and_new_event_having_timeline_and_tags(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])
        errorMessage = 'division by zero'
        errorMessageObj = 'division by zero'
        # add timeline to first tracker
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])
        event = tracker.captureMessage(errorMessage)
        # event = tracker.getCurrentEvent()

        # add timeline and tag to second tracker
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])
        tag = {"key": "location", "value": "Warsaw"}
        tracker.setTag(tag['key'], tag['value'])
        newEvent = None
        try:
            divByZero = 1 / 0
        except Exception as ex:
            newEvent = tracker.captureException(ex)
            # newEvent = tracker.getCurrentEvent()

        # ensure that the first event have a type message, same error message and two timeline (one custom, one generic)
        self.assertEqual(event["type"], 'message')
        self.assertEqual(event["content"]["message"], errorMessage)
        self.assertEqual(len(event["timeline"]), 2)
        self.assertEqual(len(event["tags"]), 1)  # the default event tag added

        # ensure that the second event have a type exception, same error message and 2 tags
        self.assertEqual(newEvent["type"], 'exception')
        self.assertEqual(newEvent["content"]["message"], errorMessageObj)
        self.assertEqual(len(newEvent["timeline"]), 2)
        self.assertEqual(len(newEvent["tags"]),
                         2)  # the default and custom tag

    def test_should_contain_version_number_and_sdk_name_in_captured_message(
            self):
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"])

        errorMessage = 'Error Found'
        tracker.captureMessage(errorMessage)
        event = tracker.getCurrentEvent()

        self.assertIsInstance(event['sdk']['name'], str)
        self.assertGreaterEqual(
            event['sdk']['version'], r'/(([0-9])+\.([0-9])+\.([0-9])+)/'
        )  # confirm that the version follows the pattern XX.XX.XX where X is a non negative integer

    def test_should_add_code_capture_to_stack_trace_when_flag_is_passed_in_options(
            self):
        options = {"captureCodeSnippet": True}
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"], options)
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])

        event = None
        errorType = 'ZeroDivisionError'
        try:
            divByZero = 1 / 0
        except Exception as ex:
            event = tracker.captureException(ex)

        # event = tracker.getCurrentEvent()
        self.assertEqual(event["type"], 'exception')
        self.assertEqual(event["content"]["type"], errorType)
        self.assertIsInstance(event["content"]["stacktrace"], dict)
        self.assertIsInstance(event["content"]["stacktrace"]["frames"], list)

        incidentFrame = event["content"]["stacktrace"]["frames"][0]
        self.assertIn('linesBeforeError', incidentFrame)
        self.assertIn('linesAfterError', incidentFrame)
        self.assertIn('errorLine', incidentFrame)

    def test_should_not_add_code_capture_to_stack_trace_when_flag_is_passed_in_options(
            self):
        options = {"captureCodeSnippet": False}
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"], options)
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])

        event = None
        errorType = 'ZeroDivisionError'
        try:
            divByZero = 1 / 0
        except Exception as ex:
            event = tracker.captureException(ex)

        # event = tracker.getCurrentEvent()
        self.assertEqual(event["type"], 'exception')
        self.assertEqual(event["content"]["type"], errorType)
        self.assertIsInstance(event["content"]["stacktrace"], dict)
        self.assertIsInstance(event["content"]["stacktrace"]["frames"], list)

        incidentFrame = event["content"]["stacktrace"]["frames"][0]
        self.assertNotIn('linesBeforeError', incidentFrame)
        self.assertNotIn('linesAfterError', incidentFrame)
        self.assertNotIn('errorLine', incidentFrame)

    def test_should_add_code_capture_to_stack_trace_by_default_when_unwanted_flag_is_passed_in_options(
            self):
        options = {
            "captureCodeSnippet":
            "hello"  # sdk expects a true or false but it defaults to true if wrong value is sent
        }
        tracker = FyipeTracker(self.apiUrl, self.errorTracker["_id"],
                               self.errorTracker["key"], options)
        tracker.addToTimeline(self.customTimeline["category"],
                              self.customTimeline["content"],
                              self.customTimeline["type"])

        event = None
        errorType = 'ZeroDivisionError'
        try:
            divByZero = 1 / 0
        except Exception as ex:
            event = tracker.captureException(ex)

        # event = tracker.getCurrentEvent()
        self.assertEqual(event["type"], 'exception')
        self.assertEqual(event["content"]["type"], errorType)
        self.assertIsInstance(event["content"]["stacktrace"], dict)
        self.assertIsInstance(event["content"]["stacktrace"]["frames"], list)

        incidentFrame = event["content"]["stacktrace"]["frames"][0]
        self.assertIn('linesBeforeError', incidentFrame)
        self.assertIn('linesAfterError', incidentFrame)
        self.assertIn('errorLine', incidentFrame)
示例#12
0
class LoggerTest(unittest.TestCase):
    def setUp(self):
        self.apiUrl = "http://localhost:3002/api"
        self.fake = Faker()
        self.setUserObject()
        try:
            # create user
            createdUser = self.apiRequest(self.apiUrl + "/user/signup", self.user, {})

            # get token and project
            token = createdUser["tokens"]["jwtAccessToken"]
            self.header = {"Authorization": "Basic " + token}
            self.project = createdUser["project"]

            # create a component
            component = {"name": self.fake.word()}
            createdComponent = self.apiRequest(
                self.apiUrl + "/component/" + self.project["_id"],
                component,
                self.header,
            )
            self.component = createdComponent

            # create an applicationlog and set it as the global application Log.
            appLog = {"name": self.fake.word()}
            createdApplicationLog = self.apiRequest(
                self.apiUrl
                + "/application-log/"
                + self.project["_id"]
                + "/"
                + createdComponent["_id"]
                + "/create",
                appLog,
                self.header,
            )
            self.applicationLog = createdApplicationLog

        except requests.exceptions.HTTPError as error:
            print("Couldnt create an application log to run a test, Error occured: ")
            print(error)

    def setUserObject(self):
        self.user = {
            "name": self.fake.name(),
            "password": "******",
            "confirmPassword": "******",
            "email": self.fake.ascii_company_email(),
            "companyName": self.fake.company(),
            "jobRole": self.fake.job(),
            "companySize": self.fake.random_int(),
            "card": {"stripeToken": "tok_visa"},
            "subscription": {"stripePlanId": 0},
            "cardName": self.fake.credit_card_provider(),
            "cardNumber": self.fake.credit_card_number(),
            "cvv": self.fake.credit_card_security_code(),
            "expiry": self.fake.credit_card_expire(),
            "city": self.fake.city(),
            "state": self.fake.country(),
            "zipCode": self.fake.postcode(),
            "companyRole": self.fake.job(),
            "companyPhoneNumber": self.fake.phone_number(),
            "planId": "plan_GoWIYiX2L8hwzx",
            "reference": "Github",
        }
        return self

    def apiRequest(self, url, body, headers):
        response = requests.post(url, body, headers=headers)
        return response.json()

    def test_application_log_key_is_required(self):
        logger = FyipeLogger(self.apiUrl, self.applicationLog["_id"], "")
        response = logger.log("test content")
        self.assertEqual(
            "Application Log Key is required.",
            response["message"],
            "Application Log Key Required",
        )

    def test_content_is_required(self):
        logger = FyipeLogger(
            self.apiUrl, self.applicationLog["_id"], self.applicationLog["key"]
        )
        response = logger.log("")
        self.assertEqual(
            "Content to be logged is required.", response["message"], "Content Required"
        )

    def test_valid_applicaiton_log_id_is_required(self):
        logger = FyipeLogger(
            self.apiUrl, "5eec6f33d7d57033b3a7d502", self.applicationLog["key"]
        )
        response = logger.log("content")
        self.assertEqual(
            "Application Log does not exist.",
            response["message"],
            "Valid Application Log",
        )

    def test_valid_string_content_of_type_info_is_logged(self):
        log = "sample content to be logged"
        logger = FyipeLogger(
            self.apiUrl, self.applicationLog["_id"], self.applicationLog["key"]
        )
        response = logger.log(log)
        self.assertEqual(log, response["content"])
        self.assertEqual("info", response["type"])

    def test_valid_object_content_of_type_info_is_logged(self):
        log = {"location": "Atlanta", "country": "USA"}
        logger = FyipeLogger(
            self.apiUrl, self.applicationLog["_id"], self.applicationLog["key"]
        )
        response = logger.log(log)
        self.assertEqual(log["location"], response["content"]["location"])
        self.assertEqual(True, isinstance(response["content"], dict))

    def test_valid_string_content_of_type_error_is_logged(self):
        log = "sample content to be logged"
        logger = FyipeLogger(
            self.apiUrl, self.applicationLog["_id"], self.applicationLog["key"]
        )
        response = logger.error(log)
        self.assertEqual(log, response["content"])
        self.assertEqual("error", response["type"])

    def test_valid_object_content_of_type_warning_is_logged(self):
        log = "sample content to be logged"
        logger = FyipeLogger(
            self.apiUrl, self.applicationLog["_id"], self.applicationLog["key"]
        )
        response = logger.warning(log)
        self.assertEqual(log, response["content"])
        self.assertEqual("warning", response["type"])

    def test_valid_object_content_of_type_info_with_one_tag_is_logged(self):
        log = {"location": "Atlanta", "country": "USA"}
        tag = "intent"
        logger = FyipeLogger(
            self.apiUrl, self.applicationLog["_id"], self.applicationLog["key"]
        )
        response = logger.log(log, tag)
        self.assertEqual(log["location"], response["content"]["location"])
        self.assertEqual("info", response["type"])
        self.assertIsInstance(response["tags"], list)
        self.assertIn(tag, response["tags"])

    def test_valid_object_content_of_type_error_with_no_tag_is_logged(self):
        log = {"location": "Atlanta", "country": "USA"}
        logger = FyipeLogger(
            self.apiUrl, self.applicationLog["_id"], self.applicationLog["key"]
        )
        response = logger.error(log)
        self.assertEqual(log["location"], response["content"]["location"])
        self.assertEqual("error", response["type"])
        self.assertIsInstance(response["tags"], list)
        self.assertEqual(0, len(response["tags"]))

    def test_valid_object_content_of_type_warning_with_four_tags_is_logged(self):
        log = {"location": "Atlanta", "country": "USA"}
        tag = ["Enough", "python", "Error", "Serverside"]
        logger = FyipeLogger(
            self.apiUrl, self.applicationLog["_id"], self.applicationLog["key"]
        )
        response = logger.warning(log, tag)
        self.assertEqual(log["country"], response["content"]["country"])
        self.assertEqual("warning", response["type"])
        self.assertIsInstance(response["tags"], list)
        self.assertEqual(len(tag), len(response["tags"]))
        for item in tag:
            self.assertIn(item, response["tags"])

    def test_valid_object_content_of_type_warning_return_invalid_tags(self):
        log = {"location": "Atlanta", "country": "USA"}
        tag = 500
        logger = FyipeLogger(
            self.apiUrl, self.applicationLog["_id"], self.applicationLog["key"]
        )
        response = logger.warning(log, tag)
        self.assertEqual("Invalid Content Tags to be logged", response, "Invalid Tags")
示例#13
0
print("Address:\t ", fake.address())
print("Date this month:\t ", fake.date_this_month())
print("IPv6:\t ", fake.ipv6())
print("Postal code:\t ", fake.postalcode())
print("Seed:\t ", fake.seed())
print("AM/PM:\t ", fake.am_pm())
print("This year:\t ", fake.date_this_year())
print("ISBN10:\t ", fake.isbn10())
print("Postal code in state:\t ", fake.postalcode_in_state())
print("Instance:\t ", fake.seed_instance())
print("Android platform token:\t ", fake.android_platform_token())
print("Data time:\t ", fake.date_time())
print("ISBN3:\t ", fake.isbn13())
print("Postal code plus 4:\t ", fake.postalcode_plus4())
print("Sentence:\t ", fake.sentence())
print("Email:\t ", fake.ascii_company_email())
print("Date time add:\t ", fake.date_time_ad())
print("ISO8601:\t ", fake.iso8601())
print("Postcode:\t ", fake.postcode())
print("Sentence:\t ", fake.sentences())
print("ASCII email:\t ", fake.ascii_email())
print("Date time beween:\t ", fake.date_time_between())
print("ITIN:\t ", fake.itin())
print("Postcode in state:\t ", fake.postcode_in_state())
# print("Set formatter:\t ", fake.set_formatter())
print("ASCII free email:\t ", fake.ascii_free_email())
print("Date time between dates:\t ", fake.date_time_between_dates())
print("Fake job:\t ", fake.job())
print("Prefix:\t ", fake.prefix())
print("SHA1:\t ", fake.sha1())
print("ASCII safe email:\t ", fake.ascii_safe_email())
示例#14
0
class Generator:
    def __init__(self, locale='zh_CN'):
        self.fake = Faker(locale)

    """一些生成器方法,生成姓名,手机号"""

    def random_phone_number(self):
        """随机手机号"""
        return self.fake.phone_number()

    def random_name(self):
        """随机姓名"""
        return self.fake.name()

    def random_ssn(self):
        """随机身份证号"""
        return self.fake.ssn()

    def random_number(self, digits=18):
        """digits=18的随机数"""
        return self.fake.random_number(digits, fix_len=True)

    def random_address(self):
        """随机地址"""
        return self.fake.address()

    def random_post_code(self):
        """随机邮编"""
        return self.fake.postcode()

    def random_email(self):
        """随机邮箱地址"""
        return self.fake.ascii_company_email()

    def credit_card_number(self):
        """随机银行卡号"""
        return self.fake.credit_card_number()

    def random_company_name(self):
        """随机公司名称"""
        return self.fake.company()

    def random_ipv4(self):
        """随机IPV4地址"""
        return self.fake.ipv4()

    def random_str(self, min_chars=0, max_chars=8):
        """长度在最大值与最小值之间的随机字符串"""
        return self.fake.pystr(min_chars=min_chars, max_chars=max_chars)

    def factory_generate_ids(self, starting_id=1, increment=1):
        """ 返回一个生成器函数,调用这个函数产生生成器,从starting_id开始,步长为increment。 """
        def generate_started_ids():
            val = starting_id
            local_increment = increment
            while True:
                yield val
                val += local_increment

        return generate_started_ids

    def factory_choice_generator(self, values):
        """ 返回一个生成器函数,调用这个函数产生生成器,从给定的list中随机取一项。 """
        def choice_generator():
            my_list = list(values)
            rand = random.Random()
            while True:
                yield rand.choice(my_list)

        return choice_generator
示例#15
0
#!/usr/bin/env python
from faker import Faker
import json
fake = Faker()

data = {}

for i in range(50):
    data[i] = {}
    data[i]['email'] = fake.ascii_company_email()
    data[i]['address'] = fake.address()
    data[i]['uri'] = fake.uri()
    data[i]['latlng'] = fake.local_latlng(country_code='US')

# data_str = json.dump(data)

with open("db.json", "w") as outfile:
    json.dump(data, outfile)
示例#16
0
from faker import Faker
fake = Faker()

log = open('logs.csv', 'w')

log.write('data,ampm,bool,nome,telefone,email\n')

for _ in range(100):
    log.write(','.join([
        fake.date_time_this_decade().strftime('%m/%d/%Y'),
        fake.am_pm(),
        str(fake.pybool()),
        fake.name(),
        fake.bothify(text='??-#########', letters='123456789'),
        fake.ascii_company_email()
    ]) + '\n')