本文整理汇总了Python中student.models.Registration类的典型用法代码示例。如果您正苦于以下问题:Python Registration类的具体用法?Python Registration怎么用?Python Registration使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Registration类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
def setUp(self):
""" Setup components used by each test."""
super(SendActivationEmailTestCase, self).setUp()
self.student = UserFactory()
registration = Registration()
registration.register(self.student)
self.msg = compose_activation_email("http://www.example.com", self.student, registration)
示例2: import_user_submit
def import_user_submit(request):
message={}
if request.method == 'POST':
f=request.FILES['file']
try:
count_success=0
# --- THIS FAILS ON SING COLUMN CVS ---
# dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,")
# f.seek(0)
# r=csv.reader(f,dialect)
r=csv.reader(f,delimiter='\t', quotechar='|', quoting=csv.QUOTE_MINIMAL)
rl = []
rl.extend(r)
cohort_id=request.POST.get("cohort_id")
cohort=Cohort.objects.get(id=cohort_id)
if cohort.licences < UserProfile.objects.filter(~Q(subscription_status = "Inactive"),cohort_id=cohort_id).count() + len(rl):
raise Exception("Licences limit exceeded")
for line in rl:
exist=validate_user_cvs_line(line)
# if(exist):
# raise Exception("An user already exists, or duplicate lines.")
email=line[USER_CSV_COL_EMAIL]
import random
username=random_mark(20)
user = User(username=username, email=email, is_active=False)
user.set_password(username)
user.save()
registration = Registration()
registration.register(user)
profile=UserProfile(user=user)
# profile.transaction_id=transaction_id
# profile.email=email
# profile.username=username
profile.cohort_id=cohort_id
profile.subscription_status="Imported"
profile.save()
cea, _ = CourseEnrollmentAllowed.objects.get_or_create(course_id='PCG_Education/PEP101.1/S2016', email=email)
cea.is_active = True
cea.auto_enroll = True
cea.save()
count_success=count_success+1
# reg = Registration.objects.get(user=user)
# d = {'name': profile.name, 'key': reg.activation_key}
# subject = render_to_string('emails/activation_email_subject.txt', d)
# subject = ''.join(subject.splitlines())
# message = render_to_string('emails/activation_emailh.txt', d)
db.transaction.commit()
message={"success": True,
"message":"Success! %s users imported." % (count_success),
"count_success":count_success,
}
except Exception as e:
db.transaction.rollback()
message={'success': False,'error':'Import error: %s. At cvs line: %s, Nobody imported.' % (e,count_success+1)}
return HttpResponse(json.dumps(message))
示例3: import_user_submit
def import_user_submit(request):
message = {}
if request.method == "POST":
f = request.FILES["file"]
try:
count_success = 0
count_exist = 0
# --- THIS FAILS ON SING COLUMN CVS ---
# dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,")
# f.seek(0)
# r=csv.reader(f,dialect)
r = csv.reader(f, delimiter="\t", quotechar="|", quoting=csv.QUOTE_MINIMAL)
rl = []
rl.extend(r)
cohort_id = request.POST.get("cohort_id")
cohort = Cohort.objects.get(id=cohort_id)
if cohort.licences < UserProfile.objects.filter(cohort_id=cohort_id).count() + len(rl):
raise Exception("Licences limit exceeded")
for line in rl:
exist = validate_user_cvs_line(line)
# if(exist):
# raise Exception("An user already exists, or duplicate lines.")
email = line[USER_CVS_COL_EMAIL]
import random
username = "".join(random.sample("abcdefg&#%^*f1234567890", 20))
user = User(username=username, email=email, is_active=True)
user.set_password(username)
user.save()
registration = Registration()
registration.register(user)
profile = UserProfile(user=user)
# profile.transaction_id=transaction_id
# profile.email=email
# profile.username=username
profile.cohort_id = cohort_id
profile.subscription_status = "Imported"
profile.save()
# reg = Registration.objects.get(user=user)
# d = {'name': profile.name, 'key': reg.activation_key}
# subject = render_to_string('emails/activation_email_subject.txt', d)
# subject = ''.join(subject.splitlines())
# message = render_to_string('emails/activation_email.txt', d)
db.transaction.commit()
message = {
"success": True,
"message": "Success! %s users imported." % (count_success),
"count_exist": count_exist,
"count_success": count_success,
}
except Exception as e:
db.transaction.rollback()
message = {
"success": False,
"error": "Import error: %s. At cvs line: %s, Nobody imported." % (e, count_success + 1),
}
return HttpResponse(json.dumps(message))
示例4: _do_create_account
def _do_create_account(post_vars):
"""
Given cleaned post variables, create the User and UserProfile objects, as well as the
registration for this user.
Returns a tuple (User, UserProfile, Registration).
Note: this function is also used for creating test users.
"""
user = User(username=post_vars['username'],
email=post_vars['email'],
is_active=False)
user.set_password(post_vars['password'])
registration = Registration()
# TODO: Rearrange so that if part of the process fails, the whole process fails.
# Right now, we can have e.g. no registration e-mail sent out and a zombie
# account
try:
user.save()
except IntegrityError:
js = {'success': False}
# Figure out the cause of the integrity error
if len(User.objects.filter(username=post_vars['username'])) > 0:
js['value'] = "An account with the Public Username '" + post_vars[
'username'] + "' already exists."
js['field'] = 'username'
return HttpResponse(json.dumps(js))
if len(User.objects.filter(email=post_vars['email'])) > 0:
js['value'] = "An account with the Email '" + post_vars[
'email'] + "' already exists."
js['field'] = 'email'
return HttpResponse(json.dumps(js))
raise
registration.register(user)
profile = UserProfile(user=user)
profile.name = post_vars['name']
profile.level_of_education = post_vars.get('level_of_education')
profile.gender = post_vars.get('gender')
profile.mailing_address = post_vars.get('mailing_address')
profile.goals = post_vars.get('goals')
try:
profile.year_of_birth = int(post_vars['year_of_birth'])
except (ValueError, KeyError):
# If they give us garbage, just ignore it instead
# of asking them to put an integer.
profile.year_of_birth = None
try:
profile.save()
except Exception:
log.exception(
"UserProfile creation failed for user {0}.".format(user.id))
return (user, profile, registration)
示例5: create_user
def create_user(username,password,email,name):
user = User(username=username,
email=email,
is_active=True,
)
user.set_password(password)
user.save()
registration = Registration()
registration.register(user)
profile = UserProfile(user=user)
profile.name = name
profile.save()
示例6: setUp
def setUp(self):
super(TestActivateAccount, self).setUp()
self.username = "jack"
self.email = "[email protected]"
self.user = User.objects.create(username=self.username, email=self.email, is_active=False)
# Set Up Registration
self.registration = Registration()
self.registration.register(self.user)
self.registration.save()
示例7: create_user
def create_user(self, uname, name, password=None):
""" Creates a user """
if not uname:
return _('Must provide username')
if not name:
return _('Must provide full name')
msg = u''
if not password:
return _('Password must be supplied')
email = uname
if '@' not in email:
msg += _('email address required (not username)')
return msg
new_password = password
user = User(username=uname, email=email, is_active=True)
user.set_password(new_password)
try:
user.save()
except IntegrityError:
msg += _(u'Oops, failed to create user {user}, {error}').format(
user=user,
error="IntegrityError"
)
return msg
reg = Registration()
reg.register(user)
profile = UserProfile(user=user)
profile.name = name
profile.save()
msg += _(u'User {user} created successfully!').format(user=user)
return msg
示例8: setUp
def setUp(self):
super(TestActivateAccount, self).setUp()
self.username = "jack"
self.email = "[email protected]"
self.password = "test-password"
self.user = UserFactory.create(
username=self.username, email=self.email, password=self.password, is_active=False,
)
# Set Up Registration
self.registration = Registration()
self.registration.register(self.user)
self.registration.save()
self.platform_name = configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)
self.activation_email_support_link = configuration_helpers.get_value(
'ACTIVATION_EMAIL_SUPPORT_LINK', settings.ACTIVATION_EMAIL_SUPPORT_LINK
) or settings.SUPPORT_SITE_LINK
示例9: setUp
def setUp(self):
update_email_marketing_config(enabled=False)
self.request_factory = RequestFactory()
self.user = UserFactory.create(username='test', email=TEST_EMAIL)
self.registration = Registration()
self.registration.register(self.user)
self.request = self.request_factory.get("foo")
update_email_marketing_config(enabled=True)
# create some test course objects
self.course_id_string = 'edX/toy/2012_Fall'
self.course_id = CourseKey.from_string(self.course_id_string)
self.course_url = 'http://testserver/courses/edX/toy/2012_Fall/info'
self.site = Site.objects.get_current()
self.request.site = self.site
super(EmailMarketingTests, self).setUp()
示例10: _do_cme_create_account
def _do_cme_create_account(post_vars):
"""
Given cleaned post variables, create the User, UserProfile and CmeUserProfile objects, as well as the
registration for this user.
Returns a tuple (User, CmeUserProfile, Registration).
Since CmeUserProfile is implemented using multi-table inheritence of UserProfile, the CmeUserProfile object
will also contain all the UserProfile fields.
"""
user = User(username=post_vars['username'],
email=post_vars['email'],
is_active=False)
user.set_password(post_vars['password'])
registration = Registration()
# @todo: Rearrange so that if part of the process fails, the whole process fails.
# Right now, we can have e.g. no registration e-mail sent out and a zombie account
try:
user.save()
except IntegrityError:
json_string = {'success': False}
# Figure out the cause of the integrity error
if len(User.objects.filter(username=post_vars['username'])) > 0:
json_string['value'] = "An account with the Public Username '" + post_vars['username'] + "' already exists."
json_string['field'] = 'username'
return HttpResponse(json.dumps(json_string))
if len(User.objects.filter(email=post_vars['email'])) > 0:
json_string['value'] = "An account with the Email '" + post_vars['email'] + "' already exists."
json_string['field'] = 'email'
return HttpResponse(json.dumps(json_string))
registration.register(user)
cme_user_profile = CmeUserProfile(user=user)
#UserProfile fields
cme_user_profile.name = post_vars['name']
cme_user_profile.gender = post_vars.get('gender')
#CmeUserProfile fields
cme_user_profile.last_name = post_vars['last_name']
cme_user_profile.first_name = post_vars['first_name']
cme_user_profile.middle_initial = post_vars.get('middle_initial')
cme_user_profile.birth_date = post_vars['birth_date']
cme_user_profile.professional_designation = post_vars.get('professional_designation')
cme_user_profile.license_number = post_vars.get('license_number')
cme_user_profile.license_country = post_vars.get('license_country')
cme_user_profile.license_state = post_vars.get('license_state')
cme_user_profile.physician_status = post_vars.get('physician_status')
cme_user_profile.patient_population = post_vars.get('patient_population')
if post_vars.get('specialty') == 'Other':
cme_user_profile.specialty = post_vars.get('specialty_free')
else:
cme_user_profile.specialty = post_vars.get('specialty')
if post_vars.get('sub_specialty') == 'Other':
cme_user_profile.sub_specialty = post_vars.get('sub_specialty_free')
else:
cme_user_profile.sub_specialty = post_vars.get('sub_specialty')
cme_user_profile.affiliation = post_vars.get('affiliation')
if post_vars.get('affiliation') == 'Other':
cme_user_profile.other_affiliation = post_vars.get('other_affiliation')
else:
cme_user_profile.other_affiliation = None
cme_user_profile.sub_affiliation = post_vars.get('sub_affiliation')
cme_user_profile.sunet_id = post_vars.get('sunet_id')
cme_user_profile.stanford_department = post_vars.get('stanford_department')
cme_user_profile.address_1 = post_vars.get('address_1')
cme_user_profile.address_2 = post_vars.get('address_2')
cme_user_profile.city_cme = post_vars.get('city')
cme_user_profile.state = post_vars.get('state')
cme_user_profile.county_province = post_vars.get('county_province')
cme_user_profile.postal_code = post_vars.get('postal_code')
cme_user_profile.country_cme = post_vars.get('country')
try:
cme_user_profile.save()
except Exception:
print "Could not create cme_user_profile"
log.exception("UserProfile creation failed for user {0}.".format(user.email))
return (user, cme_user_profile, registration)
示例11: create_account
def create_account(username, password, email):
"""Create a new user account.
This will implicitly create an empty profile for the user.
WARNING: This function does NOT yet implement all the features
in `student/views.py`. Until it does, please use this method
ONLY for tests of the account API, not in production code.
In particular, these are currently missing:
* 3rd party auth
* External auth (shibboleth)
* Complex password policies (ENFORCE_PASSWORD_POLICY)
In addition, we assume that some functionality is handled
at higher layers:
* Analytics events
* Activation email
* Terms of service / honor code checking
* Recording demographic info (use profile API)
* Auto-enrollment in courses (if invited via instructor dash)
Args:
username (unicode): The username for the new account.
password (unicode): The user's password.
email (unicode): The email address associated with the account.
Returns:
unicode: an activation key for the account.
Raises:
AccountUserAlreadyExists
AccountUsernameInvalid
AccountEmailInvalid
AccountPasswordInvalid
UserAPIInternalError: the operation failed due to an unexpected error.
"""
# Validate the username, password, and email
# This will raise an exception if any of these are not in a valid format.
_validate_username(username)
_validate_password(password, username)
_validate_email(email)
# Create the user account, setting them to "inactive" until they activate their account.
user = User(username=username, email=email, is_active=False)
user.set_password(password)
try:
user.save()
except IntegrityError:
raise AccountUserAlreadyExists
# Create a registration to track the activation process
# This implicitly saves the registration.
registration = Registration()
registration.register(user)
# Create an empty user profile with default values
UserProfile(user=user).save()
# Return the activation key, which the caller should send to the user
return registration.activation_key
示例12: import_user_submit
def import_user_submit(request):
# http://www.cnblogs.com/yijun-boxing/archive/2011/04/18/2020155.html
CONTRACT_CVS_COL_CONTRACT_ID=0
CONTRACT_CVS_COL_DISTRICT_ID=1
CONTRACT_CVS_COL_EMAIL=2
CONTRACT_CVS_COL_USERNAME=3
CONTRACT_CVS_COUNT_COL=4
message={}
n=0
if request.method == 'POST':
f=request.FILES['file']
dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,")
f.seek(0)
r=csv.reader(f,dialect)
try:
for i,line in enumerate(r):
n=n+1
contract_id=line[CONTRACT_CVS_COL_CONTRACT_ID]
district_id=line[CONTRACT_CVS_COL_DISTRICT_ID]
email=line[CONTRACT_CVS_COL_EMAIL]
username=line[CONTRACT_CVS_COL_USERNAME]
for value in line:
if len(value.strip())==0:
raise Exception("Catch csv line with empty fields line")
if len(line) != CONTRACT_CVS_COUNT_COL:
raise Exception("Catch csv line of wrong fields count")
user = User(username=username, email=email, is_active=True)
user.set_password(username)
registration = Registration()
try:
user.save()
except IntegrityError:
if len(User.objects.filter(username=username)) > 0:
raise Exception("An account with the Public Username '{username}' already exists.".format(username=username))
if len(User.objects.filter(email=email)) > 0:
raise Exception("An account with the Email '{email}' already exists.".format(email=email))
registration.register(user)
profile=UserProfile(user=user)
profile.contract_id=contract_id
profile.district_id=district_id
profile.email=email
profile.username=username
profile.save()
reg = Registration.objects.get(user=user)
d = {'name': profile.name, 'key': reg.activation_key}
subject = render_to_string('emails/activation_email_subject.txt', d)
subject = ''.join(subject.splitlines())
message = render_to_string('emails/activation_email.txt', d)
try:
_res = user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
except:
log.warning('Unable to send reactivation email', exc_info=True)
return HttpResponse(json.dumps({'success': False, 'error': _('Unable to send reactivation email')}))
message={'success': True, "message":"Success! %s users imported." % (n)}
except Exception as e:
transaction.rollback()
message={'success': False,'message':'Import error: %s, At cvs line: %s' % (e,n)}
# title = forms.CharField(max_length=50)
# file = forms.FileField()
return HttpResponse(json.dumps(message))
示例13: create_user
def create_user(self, uname, name, password=None):
""" Creates a user (both SSL and regular)"""
if not uname:
return _('Must provide username')
if not name:
return _('Must provide full name')
email_domain = getattr(settings, 'SSL_AUTH_EMAIL_DOMAIN', 'MIT.EDU')
msg = u''
if settings.FEATURES['AUTH_USE_CERTIFICATES']:
if '@' not in uname:
email = '{0}@{1}'.format(uname, email_domain)
else:
email = uname
if not email.endswith('@{0}'.format(email_domain)):
# Translators: Domain is an email domain, such as "@gmail.com"
msg += _('Email address must end in {domain}').format(domain="@{0}".format(email_domain))
return msg
mit_domain = 'ssl:MIT'
if ExternalAuthMap.objects.filter(external_id=email,
external_domain=mit_domain):
msg += _('Failed - email {email_addr} already exists as {external_id}').format(
email_addr=email,
external_id="external_id"
)
return msg
new_password = generate_password()
else:
if not password:
return _('Password must be supplied if not using certificates')
email = uname
if '@' not in email:
msg += _('email address required (not username)')
return msg
new_password = password
user = User(username=uname, email=email, is_active=True)
user.set_password(new_password)
try:
user.save()
except IntegrityError:
msg += _('Oops, failed to create user {user}, {error}').format(
user=user,
error="IntegrityError"
)
return msg
reg = Registration()
reg.register(user)
profile = UserProfile(user=user)
profile.name = name
profile.save()
if settings.FEATURES['AUTH_USE_CERTIFICATES']:
credential_string = getattr(settings, 'SSL_AUTH_DN_FORMAT_STRING',
'/C=US/ST=Massachusetts/O=Massachusetts Institute of Technology/OU=Client CA v1/CN={0}/emailAddress={1}')
credentials = credential_string.format(name, email)
eamap = ExternalAuthMap(
external_id=email,
external_email=email,
external_domain=mit_domain,
external_name=name,
internal_password=new_password,
external_credentials=json.dumps(credentials),
)
eamap.user = user
eamap.dtsignup = timezone.now()
eamap.save()
msg += _('User {user} created successfully!').format(user=user)
return msg
示例14: handle
def handle(self, *args, **options):
while True:
uname = raw_input('username: ')
if User.objects.filter(username=uname):
print "username %s already taken" % uname
else:
break
make_eamap = False
if raw_input('Create MIT ExternalAuth? [n] ').lower() == 'y':
email = '%[email protected]' % uname
if not email.endswith('@MIT.EDU'):
print "Failed - email must be @MIT.EDU"
sys.exit(-1)
mit_domain = 'ssl:MIT'
if ExternalAuthMap.objects.filter(external_id=email, external_domain=mit_domain):
print "Failed - email %s already exists as external_id" % email
sys.exit(-1)
make_eamap = True
password = GenPasswd(12)
# get name from kerberos
try:
kname = os.popen("finger %s | grep 'name:'" % email).read().strip().split('name: ')[1].strip()
except:
kname = ''
name = raw_input('Full name: [%s] ' % kname).strip()
if name == '':
name = kname
print "name = %s" % name
else:
while True:
password = getpass()
password2 = getpass()
if password == password2:
break
print "Oops, passwords do not match, please retry"
while True:
email = raw_input('email: ')
if User.objects.filter(email=email):
print "email %s already taken" % email
else:
break
name = raw_input('Full name: ')
user = User(username=uname, email=email, is_active=True)
user.set_password(password)
try:
user.save()
except IntegrityError:
print "Oops, failed to create user %s, IntegrityError" % user
raise
r = Registration()
r.register(user)
up = UserProfile(user=user)
up.name = name
up.save()
if make_eamap:
credentials = "/C=US/ST=Massachusetts/O=Massachusetts Institute of Technology/OU=Client CA v1/CN=%s/emailAddress=%s" % (name, email)
eamap = ExternalAuthMap(external_id=email,
external_email=email,
external_domain=mit_domain,
external_name=name,
internal_password=password,
external_credentials=json.dumps(credentials),
)
eamap.user = user
eamap.dtsignup = datetime.datetime.now(UTC)
eamap.save()
print "User %s created successfully!" % user
if not raw_input('Add user %s to any groups? [n] ' % user).lower() == 'y':
sys.exit(0)
print "Here are the groups available:"
groups = [str(g.name) for g in Group.objects.all()]
print groups
completer = MyCompleter(groups)
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
while True:
gname = raw_input("Add group (tab to autocomplete, empty line to end): ")
if not gname:
break
if not gname in groups:
print "Unknown group %s" % gname
continue
g = Group.objects.get(name=gname)
user.groups.add(g)
#.........这里部分代码省略.........
示例15: EmailMarketingTests
class EmailMarketingTests(TestCase):
"""
Tests for the EmailMarketing signals and tasks classes.
"""
shard = 4
def setUp(self):
update_email_marketing_config(enabled=False)
self.request_factory = RequestFactory()
self.user = UserFactory.create(username='test', email=TEST_EMAIL)
self.registration = Registration()
self.registration.register(self.user)
self.request = self.request_factory.get("foo")
update_email_marketing_config(enabled=True)
# create some test course objects
self.course_id_string = 'edX/toy/2012_Fall'
self.course_id = CourseKey.from_string(self.course_id_string)
self.course_url = 'http://testserver/courses/edX/toy/2012_Fall/info'
self.site = Site.objects.get_current()
self.site_domain = self.site.domain
self.request.site = self.site
super(EmailMarketingTests, self).setUp()
@freeze_time(datetime.datetime.now())
@patch('email_marketing.signals.crum.get_current_request')
@patch('sailthru.sailthru_client.SailthruClient.api_post')
def test_drop_cookie(self, mock_sailthru, mock_get_current_request):
"""
Test add_email_marketing_cookies
"""
response = JsonResponse({
"success": True,
"redirect_url": 'test.com/test',
})
self.request.COOKIES['anonymous_interest'] = 'cookie_content'
mock_get_current_request.return_value = self.request
cookies = {'cookie': 'test_cookie'}
mock_sailthru.return_value = SailthruResponse(JsonResponse({'keys': cookies}))
with LogCapture(LOGGER_NAME, level=logging.INFO) as logger:
add_email_marketing_cookies(None, response=response, user=self.user)
logger.check(
(LOGGER_NAME, 'INFO',
'Started at {start} and ended at {end}, time spent:{delta} milliseconds'.format(
start=datetime.datetime.now().isoformat(' '),
end=datetime.datetime.now().isoformat(' '),
delta=0)
),
(LOGGER_NAME, 'INFO',
'sailthru_hid cookie:{cookies[cookie]} successfully retrieved for user {user}'.format(
cookies=cookies,
user=TEST_EMAIL)
)
)
mock_sailthru.assert_called_with('user',
{'fields': {'keys': 1},
'cookies': {'anonymous_interest': 'cookie_content'},
'id': TEST_EMAIL,
'vars': {'last_login_date': ANY}})
self.assertTrue('sailthru_hid' in response.cookies)
self.assertEquals(response.cookies['sailthru_hid'].value, "test_cookie")
@patch('sailthru.sailthru_client.SailthruClient.api_post')
def test_get_cookies_via_sailthu(self, mock_sailthru):
cookies = {'cookie': 'test_cookie'}
mock_sailthru.return_value = SailthruResponse(JsonResponse({'keys': cookies}))
post_parms = {
'id': self.user.email,
'fields': {'keys': 1},
'vars': {'last_login_date': datetime.datetime.now().strftime("%Y-%m-%d")},
'cookies': {'anonymous_interest': 'cookie_content'}
}
expected_cookie = get_email_cookies_via_sailthru.delay(self.user.email, post_parms)
mock_sailthru.assert_called_with('user',
{'fields': {'keys': 1},
'cookies': {'anonymous_interest': 'cookie_content'},
'id': TEST_EMAIL,
'vars': {'last_login_date': ANY}})
self.assertEqual(cookies['cookie'], expected_cookie.result)
@patch('sailthru.sailthru_client.SailthruClient.api_post')
def test_drop_cookie_error_path(self, mock_sailthru):
"""
test that error paths return no cookie
"""
response = JsonResponse({
"success": True,
"redirect_url": 'test.com/test',
})
mock_sailthru.return_value = SailthruResponse(JsonResponse({'keys': {'cookiexx': 'test_cookie'}}))
add_email_marketing_cookies(None, response=response, user=self.user)
self.assertFalse('sailthru_hid' in response.cookies)
#.........这里部分代码省略.........