def create_payment(delivery_group):
order = delivery_group.order
status = random.choice(
[PaymentStatus.WAITING, PaymentStatus.PREAUTH, PaymentStatus.CONFIRMED])
payment = Payment.objects.create(
order=order,
status=status,
variant='default',
transaction_id=str(fake.random_int(1, 100000)),
currency=settings.DEFAULT_CURRENCY,
total=order.get_total().gross,
delivery=delivery_group.shipping_price.gross,
customer_ip_address=fake.ipv4(),
billing_first_name=order.billing_address.first_name,
billing_last_name=order.billing_address.last_name,
billing_address_1=order.billing_address.street_address_1,
billing_city=order.billing_address.city,
billing_postcode=order.billing_address.postal_code,
billing_country_code=order.billing_address.country)
if status == PaymentStatus.CONFIRMED:
payment.captured_amount = payment.total
payment.save()
return payment
python类create()的实例源码
def user_creator(num_user):
"""Create users from an Italian-like context. Due to param in factory create 'it_iT'."""
for i in range(num_user):
user_uuid = fake.uuid4()
first_name = fake.first_name()
last_name = fake.last_name()
email_provider = fake.free_email_domain()
email_user = '{}.{}@{}'.format(
first_name.lower(), last_name.lower(), email_provider)
password = fake.password(length=3, special_chars=False, digits=True,
upper_case=True, lower_case=False)
User.create(
uuid=user_uuid,
first_name=first_name,
last_name=last_name,
email=email_user,
password=User.hash_password(password)
)
def item_creator(num_item):
LIST_CATEGORIES = ['scarpe', 'accessori', 'abbigliamento uomo', 'abbigliamento donna']
for i in range(num_item):
item_id = fake.uuid4()
item_name = fake.sentence(nb_words=3, variable_nb_words=True)
item_price = fake.pyfloat(left_digits=2, right_digits=2, positive=True)
item_category = random.choice(LIST_CATEGORIES)
item = Item.create(
uuid=item_id,
name=item_name,
price=item_price,
description=fake.paragraph(
nb_sentences=3, variable_nb_sentences=True),
availability=random.randint(35, 60),
category=item_category,
)
picture_creator(num_item, i, item)
def make_mock_transfer_sub(from_org, to_org):
sub = factories.FormSubmissionWithOrgsFactory.create(
organizations=[from_org])
application = sub.applications.first()
author = from_org.profiles.first().user
# make a status_update prior to transfer
factories.StatusUpdateWithNotificationFactory.create(
application=application, author=author)
transfer, *stuff = services.transfers_service.transfer_application(
author=author, application=application,
to_organization=to_org, reason="Transporter malfunction")
message = 'Your case has been transferred to {}.\n{}'.format(
to_org.name, to_org.short_confirmation_message)
factories.StatusNotificationFactory.create(
status_update=transfer.status_update, base_message=message,
sent_message=message)
return sub
def test_bad_mac_doesnt_evaluate():
fake= Factory().create()
assert mac_audit.evaluate_mac(
_strip_mac(fake.mac_address()),
None
) == 0
assert mac_audit.evaluate_mac(
None,
None
) == 0
assert mac_audit.evaluate_mac(
None,
_strip_mac(fake.mac_address()),
) == 0
def c_table (Table, t_config): # create dynamo DB tables
"""
try to create table, if it errors tables exist,
drop the tables, and then rerun the function to create again.
"""
try:
print "INFO :: Creating %s Table....." % Table
db_r.create_table(
AttributeDefinitions = t_config[Table]['AttributeDefinitions'],
TableName=Table,
KeySchema = t_config[Table]['KeySchema'],
ProvisionedThroughput=t_config[Table]['ProvisionedThroughput']
)
print "INFO :: Waiting for completion..."
db_r.Table(Table).wait_until_exists()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "ResourceInUseException":
print "INFO :: Learning Online %s Table exists, deleting ...." % Table
db_r.Table(Table).delete()
print "INFO :: Waiting for delete.."
db_r.Table(Table).wait_until_not_exists()
c_table (Table, t_config)
else:
print "Unknown Error"
#------------------------------------------------------------------------------
def c_table (Table, t_config): # create dynamo DB tables
"""
try to create table, if it errors tables exist,
drop the tables, and then rerun the function to create again.
"""
try:
print "INFO :: Creating %s Table....." % Table
db_r.create_table(
AttributeDefinitions = t_config[Table]['AttributeDefinitions'],
TableName=Table,
KeySchema = t_config[Table]['KeySchema'],
ProvisionedThroughput=t_config[Table]['ProvisionedThroughput']
)
print "INFO :: Waiting for completion..."
db_r.Table(Table).wait_until_exists()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "ResourceInUseException":
print "INFO :: Learning Online %s Table exists, deleting ...." % Table
db_r.Table(Table).delete()
print "INFO :: Waiting for delete.."
db_r.Table(Table).wait_until_not_exists()
c_table (Table, t_config)
else:
print "Unknown Error"
#------------------------------------------------------------------------------
def c_table (Table, t_config): # create dynamo DB tables
"""
try to create table, if it errors tables exist,
drop the tables, and then rerun the function to create again.
"""
try:
print "INFO :: Creating %s Table....." % Table
db_r.create_table(
AttributeDefinitions = t_config[Table]['AttributeDefinitions'],
TableName=Table,
KeySchema = t_config[Table]['KeySchema'],
ProvisionedThroughput=t_config[Table]['ProvisionedThroughput']
)
print "INFO :: Waiting for completion..."
db_r.Table(Table).wait_until_exists()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "ResourceInUseException":
print "INFO :: Learning Online %s Table exists, deleting ...." % Table
db_r.Table(Table).delete()
print "INFO :: Waiting for delete.."
db_r.Table(Table).wait_until_not_exists()
c_table (Table, t_config)
else:
print "Unknown Error"
#------------------------------------------------------------------------------
def c_table (Table, t_config): # create dynamo DB tables
"""
try to create table, if it errors tables exist,
drop the tables, and then rerun the function to create again.
"""
try:
print "INFO :: Creating %s Table....." % Table
db_r.create_table(
AttributeDefinitions = t_config[Table]['AttributeDefinitions'],
TableName=Table,
KeySchema = t_config[Table]['KeySchema'],
ProvisionedThroughput=t_config[Table]['ProvisionedThroughput']
)
print "INFO :: Waiting for completion..."
db_r.Table(Table).wait_until_exists()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "ResourceInUseException":
print "INFO :: Learning Online %s Table exists, deleting ...." % Table
db_r.Table(Table).delete()
print "INFO :: Waiting for delete.."
db_r.Table(Table).wait_until_not_exists()
c_table (Table, t_config)
else:
print "Unknown Error"
#------------------------------------------------------------------------------
def setUp(self):
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-setuid-sandbox")
"""Setup the test driver and create test users"""
self.driver = webdriver.Chrome(chrome_options=chrome_options)
self.driver.get(self.get_server_url())
email_admin = test_admin_email
db.session.commit()
db.drop_all()
db.create_all()
user_datastore.create_user(email=test_admin_email, username=test_admin_username, password=test_admin_password)
user_datastore.create_user(email=test_user_final_email, username=test_user_final_username, password=test_user_final_password)
user_datastore.find_or_create_role(name='admin', description='Administrator')
user_datastore.find_or_create_role(name='end-user', description='End user')
user_datastore.add_role_to_user(email_admin, 'admin')
db.session.commit()
def create_challenge(title, start_date, end_date, host_team):
"""
Creates a challenge.
"""
evaluation_script = open(os.path.join(settings.BASE_DIR, 'examples', 'example1', 'string_matching.zip'), 'rb')
Challenge.objects.create(
title=title,
short_description=fake.paragraph(),
description=fake.paragraph(),
terms_and_conditions=fake.paragraph(),
submission_guidelines=fake.paragraph(),
evaluation_details=fake.paragraph(),
evaluation_script=SimpleUploadedFile(evaluation_script.name, evaluation_script.read()),
approved_by_admin=True,
creator=host_team,
published=True,
enable_forum=True,
anonymous_leaderboard=False,
start_date=start_date,
end_date=end_date,
)
print("Challenge created with title: {} creator: {} start_date: {} end_date: {}".format(title,
host_team.team_name,
start_date, end_date))
def create_challenge_phases(challenge, number_of_phases=1):
"""
Creates challenge phases for the created challenges and returns it.
"""
challenge_phases = []
for i in range(number_of_phases):
name = "{} Phase".format(fake.first_name())
with open(os.path.join(settings.BASE_DIR, 'examples', 'example1', 'test_annotation.txt'), 'rb') as data_file:
data = data_file.read()
data = data or None
challenge_phase = ChallengePhase.objects.create(
name=name,
description=fake.paragraph(),
leaderboard_public=True,
is_public=True,
start_date=challenge.start_date,
end_date=challenge.end_date,
challenge=challenge,
test_annotation=SimpleUploadedFile(fake.file_name(extension="txt"), data, content_type="text/plain"),
codename="{}{}".format("phase", i + 1),
)
challenge_phases.append(challenge_phase)
print("Challenge Phase created with name: {} challenge: {}".format(name, challenge.title))
return challenge_phases
def setUp(self):
"""
Set up reusable fake data.
"""
self.user = UserFactory.create(is_staff=True, is_active=True)
self.user.set_password("QWERTY")
self.user.save()
self.client = Client()
self.demo_course_1 = FAKE_PROGRAM_RESPONSE3['courses'][0]
self.demo_course_2 = FAKE_PROGRAM_RESPONSE3['courses'][1]
self.demo_course_id1 = FAKE_PROGRAM_RESPONSE3['courses'][0]['key']
self.demo_course_id2 = FAKE_PROGRAM_RESPONSE3['courses'][1]['key']
self.demo_course_ids = [self.demo_course_id1, self.demo_course_id2]
self.dummy_program_uuid = FAKE_PROGRAM_RESPONSE3['uuid']
self.dummy_program = FAKE_PROGRAM_RESPONSE3
super(TestProgramEnrollmentView, self).setUp()
def setUp(self):
self.user = UserFactory.create(is_staff=True, is_active=True)
self.user.set_password("QWERTY")
self.user.save()
self.client = Client()
self.demo_course_id = 'course-v1:edX+DemoX+Demo_Course'
self.dummy_demo_course_modes = [
{
"slug": "professional",
"name": "Professional Track",
"min_price": 100,
"sku": "sku-audit",
},
{
"slug": "audit",
"name": "Audit Track",
"min_price": 0,
"sku": "sku-audit",
},
]
super(TestHandleConsentEnrollmentView, self).setUp()
def setUp(self):
self.user = UserFactory.create(is_staff=True, is_active=True)
self.user.set_password("QWERTY")
self.user.save()
self.client = Client()
self.demo_course_id = 'course-v1:edX+DemoX+Demo_Course'
self.dummy_demo_course_modes = [
{
"slug": "professional",
"name": "Professional Track",
"min_price": 100,
"sku": "sku-professional",
},
{
"slug": "audit",
"name": "Audit Track",
"min_price": 0,
"sku": "sku-audit",
},
]
self.faker = FakerFactory.create()
self.provider_id = self.faker.slug() # pylint: disable=no-member
super(TestCourseEnrollmentView, self).setUp()
def test_string_conversion(self, method):
"""
Test ``EnterpriseCustomerCatalog`` conversion to string.
"""
faker = FakerFactory.create()
uuid = faker.uuid4() # pylint: disable=no-member
name = 'EnterpriseWithACatalog'
enterprise_catalog = EnterpriseCustomerCatalog(
uuid=uuid,
enterprise_customer=factories.EnterpriseCustomerFactory(name=name)
)
expected_str = "<EnterpriseCustomerCatalog with uuid '{uuid}' for EnterpriseCustomer {name}>".format(
uuid=uuid,
name=name
)
self.assertEqual(method(enterprise_catalog), expected_str)
def test_project_estimate(self):
project = Project.objects.create(
client=self.client,
name='Testing',
estimate=5000.00
)
task = Task.objects.create(
name='Testing',
hourly_rate=100.00
)
Entry.objects.create(
project=project,
user=self.user,
task=task,
duration=timedelta(hours=10),
note='Creating tests for the core app'
)
self.assertEqual(project.get_percent_done(), 20)
def logIn(self):
self.user = User.objects.create_user(self.profile['username'],
self.profile['mail'],
self.profile['password'])
site_permission = SitePermission.objects.create(user=self.user)
site_permission.sites.set(Site.objects.filter(id=1))
site_permission.save()
self.driver.get('%s%s' % (self.live_server_url, '/login/'))
username_input = self.find(By.NAME, 'username')
self.clear(username_input)
username_input.send_keys(self.profile['username'])
password_input = self.find(By.NAME, 'password')
self.clear(password_input)
password_input.send_keys(self.profile['password'])
self.find(By.NAME, 'login').click()
self.waitForPresence((By.ID, 'nav-app'))
def init_api_test_data():
"""
Generates fake data, starts an HttpClient session, creates a fake user and
logs that user in.
"""
call_command('migrate', verbosity=0)
call_command('fake', verbosity=0, iterations=1)
c = HttpClient()
fake_user = fake.simple_profile()
fake_password = fake.password()
user = User.objects.create_user(fake_user['username'], fake_user['mail'],
fake_password)
site_permission = SitePermission.objects.create(user=user)
site_permission.sites.set(Site.objects.filter(id=1))
site_permission.save()
user = User.objects.get(username=fake_user['username'])
c.login(username=fake_user['username'], password=fake_password)
return [c, user]
def populate_model(model, instances, create=True):
model_fields = filter((lambda x: isinstance(x, models.Field)),
model._meta.get_fields())
kwargs = {}
# Outstanding instances in case of Many-to-Many relations.
outstanding = {}
for model_field in model_fields:
if isinstance(model_field, models.AutoField):
continue
field_value, isoutstanding = generate_field_value(
model_field, instances)
if isoutstanding:
outstanding[model_field.name] = field_value
else:
kwargs[model_field.name] = field_value
if not create:
return kwargs
return create_instance(model, kwargs, outstanding)
def faker():
return Factory.create()
def create_product(**kwargs):
defaults = {
'name': fake.company(),
'price': fake.price(),
'description': '\n\n'.join(fake.paragraphs(5))}
defaults.update(kwargs)
return Product.objects.create(**defaults)
def create_stock(variant, **kwargs):
default_location = StockLocation.objects.get_or_create(
name=STOCK_LOCATION)[0]
defaults = {
'variant': variant,
'location': default_location,
'quantity': fake.random_int(1, 50)}
defaults.update(kwargs)
return Stock.objects.create(**defaults)
def create_variant(product, **kwargs):
defaults = {
'product': product}
defaults.update(kwargs)
variant = ProductVariant.objects.create(**defaults)
create_stock(variant)
return variant
def create_address():
address = Address.objects.create(
first_name=fake.first_name(),
last_name=fake.last_name(),
street_address_1=fake.street_address(),
city=fake.city(),
postal_code=fake.postcode(),
country=fake.country_code())
return address
def create_order_line(delivery_group):
product = Product.objects.all().order_by('?')[0]
variant = product.variants.all()[0]
return OrderedItem.objects.create(
delivery_group=delivery_group,
product=product,
product_name=product.name,
product_sku=variant.sku,
quantity=random.randrange(1, 5),
unit_price_net=product.price.net,
unit_price_gross=product.price.gross)
def create_fake_order():
user = random.choice([None, User.objects.filter(
is_superuser=False).order_by('?').first()])
if user:
user_data = {
'user': user,
'billing_address': user.default_billing_address,
'shipping_address': user.default_shipping_address}
else:
address = create_address()
user_data = {
'billing_address': address,
'shipping_address': address,
'user_email': get_email(
address.first_name, address.last_name)}
order = Order.objects.create(**user_data)
order.change_status(OrderStatus.PAYMENT_PENDING)
delivery_group = create_delivery_group(order)
lines = create_order_lines(delivery_group, random.randrange(1, 5))
order.total = sum(
[line.get_total() for line in lines], delivery_group.shipping_price)
order.save()
payment = create_payment(delivery_group)
if payment.status == PaymentStatus.CONFIRMED:
order.change_status(OrderStatus.FULLY_PAID)
if random.choice([True, False]):
order.change_status(OrderStatus.SHIPPED)
return order
def create_fake_sale():
sale = Sale.objects.create(
name='Happy %s day!' % fake.word(),
type=Sale.PERCENTAGE,
value=random.choice([10, 20, 30, 40, 50]))
for product in Product.objects.all().order_by('?')[:4]:
sale.products.add(product)
return sale
def create_shipping_methods():
shipping_method = ShippingMethod.objects.create(name='UPC')
shipping_method.price_per_country.create(price=fake.price())
yield 'Shipping method #%d' % shipping_method.id
shipping_method = ShippingMethod.objects.create(name='DHL')
shipping_method.price_per_country.create(price=fake.price())
yield 'Shipping method #%d' % shipping_method.id
def create_nickname():
faker = Factory.create(settings.LANGUAGE_CODE)
return faker.first_name_female()