function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def test_user_login_valid_username_user_not_exists(self): response = self.client.post(reverse('user_login_api'), {'app_key': self.api_key, 'username': 'test_username', 'password': 'password'})
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_user_login_valid_email_user_not_exists(self): response = self.client.post(reverse('user_login_api'), {'app_key': self.api_key, 'username': 'api_login_email@email.com', 'password': '123456'})
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_user_login_success_with_username(self): response = self.client.post(reverse('user_login_api'), {'app_key': self.api_key, 'username': 'api_login', 'password': '123456'})
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def test_user_login_success_with_email(self): response = self.client.post(reverse('user_login_api'), {'app_key': self.api_key, 'username': 'api_login@email.com', 'password': '123456'})
OlegKlimenko/Plamber
[ 9, 1, 9, 28, 1487368387 ]
def setUp(self): self.converter = BytesCanUplinkConverter()
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def test_wrong_type(self): can_data = [0, 1, 0, 0, 0] configs = [{ "key": "var", "is_ts": True, "type": "wrong_type" }] tb_data = self.converter.convert(configs, can_data) self.assertTrue(self._has_no_data(tb_data))
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def test_bool_false(self): can_data = [1, 0, 1, 1, 1] configs = [{ "key": "boolVar", "is_ts": False, "type": "bool", "start": 1 }] tb_data = self.converter.convert(configs, can_data) self.assertFalse(tb_data["attributes"]["boolVar"])
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def test_int_big_byteorder(self): self._test_int("int", "big")
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def test_long_big_byteorder(self): self._test_int("long", "big")
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def _test_float_point_number(self, type, byteorder): float_value = uniform(-3.1415926535, 3.1415926535) can_data = [0, 0] configs = [{ "key": type + "Var", "is_ts": True, "type": type, "start": len(can_data), "length": 4 if type[0] == "f" else 8, "byteorder": byteorder }] can_data.extend(_struct.pack((">" if byteorder[0] == "b" else "<") + type[0], float_value)) tb_data = self.converter.convert(configs, can_data) self.assertTrue(isclose(tb_data["telemetry"][type + "Var"], float_value, rel_tol=1e-05))
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def test_float_little_byteorder(self): self._test_float_point_number("float", "little")
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def test_double_little_byteorder(self): self._test_float_point_number("double", "little")
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def test_string_default_ascii_encoding(self): self._test_string()
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def _test_eval_int(self, number, strict_eval, expression): can_data = number.to_bytes(1, "big", signed=(number < 0)) # By default the strictEval flag is True configs = [{ "key": "var", "is_ts": True, "type": "int", "start": 0, "length": 1, "byteorder": "big", "signed": number < 0, "expression": expression, "strictEval": strict_eval }] return self.converter.convert(configs, can_data)
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def test_strict_eval(self): number = randint(-128, 256) tb_data = self._test_eval_int(number, True, "value * value") self.assertEqual(tb_data["telemetry"]["var"], number * number)
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def test_multiple_valid_configs(self): bool_value = True int_value = randint(0, 256) can_data = [0, int(bool_value), int_value, 0, 0, 0] configs = [ { "key": "boolVar", "type": "boolean", "is_ts": True, "start": 1 }, { "key": "intVar", "type": "int", "is_ts": False, "start": 2, "length": 4, "byteorder": "little", "signed": False } ] tb_data = self.converter.convert(configs, can_data) self.assertEqual(tb_data["telemetry"]["boolVar"], bool_value) self.assertEqual(tb_data["attributes"]["intVar"], int_value)
thingsboard/thingsboard-gateway
[ 1270, 690, 1270, 21, 1483594863 ]
def __init__(self, inputname=None, initfilename=None, startsol=-1, endsol=-1, initpriorsols=False, shotnoisefilt=0): """LIBSData(inputname="", sol=-1) Read in LIBS (ChemCam) data in CSV format from inputname. If inputname ends in .csv, treat it as a CSV file. If inputname ends in .pkl, treat it as a pickled file. Otherwise, treat it as a directory and look for a .pkl file inside; if not found, generate it with contents from all .csv files present. If present, also read in data from initfilename (must be .csv). This data will be used to initialize the DEMUD model. Optionally, specify a sol range (startsol-endsol) for data to analyze. Optionally, use data prior to startsol to initialize the model. Optionally, specify the width of a median filter to apply. """ input_type = inputname[-3:] if input_type == 'csv': filename = inputname expname = 'libs-' + \ os.path.splitext(os.path.basename(filename))[0] #filename[filename.rfind('/')+1:filename.find('.')] elif input_type == 'pkl': if shotnoisefilt > 0: #filename = inputname[:-4] + ('-snf%d.pkl' % shotnoisefilt) filename = os.path.splitext(inputname)[0] + \ ('-snf%d.pkl' % shotnoisefilt) else: filename = inputname expname = 'libs-' + \ os.path.splitext(os.path.basename(filename))[0] #filename[filename.rfind('/')+1:filename.find('.')] else: # assume directory input_type = 'dir' #filename = inputname + '/libs-mean-norm.pkl' filename = os.path.join(inputname, 'libs-mean-norm.pkl') if shotnoisefilt > 0: #filename = filename[:-4] + ('-snf%d.pkl' % shotnoisefilt) filename = os.path.splitext(inputname)[0] + \ ('-snf%d.pkl' % shotnoisefilt) #expname = 'libs-' + inputname[inputname.rfind('/')+1:] expname = 'libs-' + os.path.basename(inputname) Dataset.__init__(self, filename, expname, initfilename) printt('Reading %s data from %s.' % (input_type, self.filename)) if input_type == 'dir' and not os.path.exists(filename): LIBSData.read_dir(inputname, filename, shotnoisefilt)
wkiri/DEMUD
[ 44, 16, 44, 1, 1442439781 ]
def readin(self, startsol=-1, endsol=-1, initpriorsols=False, shotnoisefilt=0): """readin()
wkiri/DEMUD
[ 44, 16, 44, 1, 1442439781 ]
def filter_data(self, data, labels): """filter_data(data, labels) Filter out bad quality data, using criteria provided by Nina Lanza: 1) Large, broad features (don't correspond to narrow peaks) 2) Low SNR For each item thus filtered, write out a plot of the data with an explanation: 1) Annotate in red the large, broad feature, or 2) Annotate in text the SNR. Returns updated (filtered) data and label arrays. """ n = data.shape[1] newdata = data remove_ind = [] printt("Filtering out data with large, broad features.") #for i in [78]: # test data gap #for i in [1461]: # test broad feature #for i in [3400]: # test broad feature for i in range(n): waves = range(data.shape[0]) this_data = data[waves,i] peak_ind = this_data.argmax() peak_wave = self.xvals[waves[peak_ind]] # Set min peak to examine as 30% of max min_peak = 0.15 * this_data[peak_ind] # Track red_waves: indices of bands that contribute to deciding # to filter out this item (if indeed it is). # These same wavelengths will be removed from further consideration # regardless of filtering decision red_waves = []
wkiri/DEMUD
[ 44, 16, 44, 1, 1442439781 ]
def read_dir(cls, dirname, outfile, shotnoisefilt=0): """read_dir(dirname, outfile) Read in raw LIBS data from .csv files in dirname. Pickle the result and save it to outfile. Note: does NOT update object fields. Follow this with a call to readin(). """ # First read in the target names and sol numbers. targets = {} sols = {} # Location of this file is hard-coded! # My latest version goes through sol 707. metafile = 'msl_ccam_obs.csv' with open(os.path.join(dirname, metafile)) as f: datareader = csv.reader(f) # Index targets, sols by spacecraft clock value for row in datareader: [sol, edr_type, sclk, target] = [row[i] for i in [0,1,2,5]] if edr_type != 'CL5': continue prior_targets = [t for t in targets.values() if target in t] n_prior = len(prior_targets) # Add 1 so shots are indexed from 1, not 0 targets[sclk] = target + ':%d' % (n_prior + 1) sols[sclk] = sol print 'Read %d target names from %s.' % (len(targets), metafile) print 'Now reading LIBS data from %s.' % dirname data = [] labels = [] wavelengths = [] files = os.listdir(dirname) f_ind = 0
wkiri/DEMUD
[ 44, 16, 44, 1, 1442439781 ]
def prune_and_normalize(cls, data, wavelengths, shotnoisefilt): """prune_and_normalize(cls, data, wavelengths, shotnoisefilt) Subset LIBS data to only use wavelengths below 850 nm, set negative values to zero, then normalize responses for each of the three spectrometers. If shotnoisefilt >= 3, run a median filter on the data with width as specified. Return the pruned and normalized data. """ print 'Pruning and normalizing the data.' # Only use data between 270 and 820 nm (ends are noisy) use = np.where(np.logical_and(wavelengths >= 270, wavelengths < 820))[0] # Instead of stripping these bands out now, first do shot noise # filtering (if desired). Then strip the bands later. # If desired, apply a median filter to strip out impulsive noise # Note: this is slow. :) Probably can be optimized in some awesome fashion. if shotnoisefilt >= 3: printt('Filtering out shot noise with width %d.' % shotnoisefilt) # Create a vector of 0's (to ignore) and 1's (to use). fw = np.zeros((data.shape[0],1)) fw[use] = 1 data = LIBSData.medfilter(data, shotnoisefilt, fw) # Now remove bands we do not use wavelengths = wavelengths[use] data = data[use,:]
wkiri/DEMUD
[ 44, 16, 44, 1, 1442439781 ]
def medfilter(cls, data, L, fw=[]): """medfilter(cls, data, L) Filter each column of data using a window of width L. Replace each value with its median from the surrounding window. Inspired by http://staff.washington.edu/bdjwww/medfilt.py . Optionally, specify feature weights so they can factor in to the median calculation. Any zero-valued weights make the median calculation ignore those items. Values greater than zero are NOT weighted; they all participate normally. """ if data == []: print 'Error: empty data; cannot filter.' return data
wkiri/DEMUD
[ 44, 16, 44, 1, 1442439781 ]
def read_csv_data(cls, filename): data = []
wkiri/DEMUD
[ 44, 16, 44, 1, 1442439781 ]
def plot_item(self, m, ind, x, r, k, label, U, rerr, feature_weights): """plot_item(self, m, ind, x, r, k, label, U, rerr, feature_weights) Plot selection m (index ind, data in x) and its reconstruction r, with k and label to annotate of the plot. Use fancy ChemCam elemental annotations. If feature_weights are specified, omit any 0-weighted features from the plot. """ if x == [] or r == []: print "Error: No data in x and/or r." return
wkiri/DEMUD
[ 44, 16, 44, 1, 1442439781 ]
def find_closest(cls, w, emissions, min_match_nm): if min_match_nm == 0: b = -1 elt = 'None' return (b,elt) # Binary search for best match waves = emissions.keys() waves.sort() lo_b = 0 hi_b = len(waves) b = int(math.floor((hi_b + lo_b) / 2)) while lo_b < hi_b: diff = float(waves[b]) - w ldiff = float('Inf') if b-1 >= 0: ldiff = float(waves[b-1]) - w rdiff = float('Inf') if b+1 <= len(waves)-1: rdiff = float(waves[b+1]) - w if abs(diff) < abs(ldiff) and abs(diff) < abs(rdiff): break if diff > 0: # too high hi_b = b else: # too low lo_b = b b = int(math.floor((hi_b + lo_b) / 2)) # Quality control: must be within match nm if abs(float(waves[b]) - w) > min_match_nm: b = -1 elt = 'None' else: elt = emissions[waves[b]]
wkiri/DEMUD
[ 44, 16, 44, 1, 1442439781 ]
def __init__(self,token,imgfile=None,pointsfile=None): if token not in rs.TOKENS: raise ValueError("Token %s not found."%(token)) self._token = token self._imgfile = imgfile self._pointsfile = pointsfile self._img = None # img data self._points = None # [[x],[y],[z],[v]] self._shape = None # (x,y,z) self._max = None # max value
NeuroDataDesign/seelviz
[ 1, 2, 1, 14, 1472747234 ]
def loadEqImg(self, path=None, info=False): if path is None: path = rs.RAW_DATA_PATH pathname = path+self._token+".nii" img = nib.load(pathname) if info: print(img) self._img = img.get_data()[:,:,:,0] self._shape = self._img.shape self._max = np.max(self._img) print("Image Loaded: %s"%(pathname)) return self
NeuroDataDesign/seelviz
[ 1, 2, 1, 14, 1472747234 ]
def getMax(self): return self._max
NeuroDataDesign/seelviz
[ 1, 2, 1, 14, 1472747234 ]
def getHistogram(self,bins,range,density=True): if self._img is None: raise ValueError("Img haven't loaded, please call loadImg() first.") return np.histogram(self._img.flatten(), bins=bins, range=range, density=density)
NeuroDataDesign/seelviz
[ 1, 2, 1, 14, 1472747234 ]
def loadPoints(self,path=None): if path is None: path = rs.POINTS_DATA_PATH pathname = path+self._token+".csv" self._points = np.loadtxt(pathname,dtype=np.int16,delimiter=',') print("Points Loaded: %s"%(pathname)) return self
NeuroDataDesign/seelviz
[ 1, 2, 1, 14, 1472747234 ]
def centralize(self): # Centralize the data # use mean or median centerX = np.mean(self._points[:,0]) centerY = np.mean(self._points[:,1]) centerZ = np.mean(self._points[:,2]) self._points[:,0] -= np.int16(centerX) self._points[:,1] -= np.int16(centerY) self._points[:,2] -= np.int16(centerZ) return self
NeuroDataDesign/seelviz
[ 1, 2, 1, 14, 1472747234 ]
def showHistogram(self,bins=255): plt.hist(self._points[:,3],bins=bins) plt.title("%s Points Histogram"%(self._token)) plt.ylabel("count") plt.xlabel("level") plt.grid() plt.show()
NeuroDataDesign/seelviz
[ 1, 2, 1, 14, 1472747234 ]
def sort_buildings(buildings): def make_sort_key(building): s = re.split(r'(\d+)([a-zA-Z]?)', building.number) if len(s) != 4: return building.street, building.number #split unsuccessful return building.street, (int(s[1]), s[2].lower()) sorted_buildings = sorted(buildings, key=make_sort_key) return sorted_buildings
agdsn/pycroft
[ 17, 9, 17, 178, 1461177396 ]
def __init__(self): super().__init__()
HazyResearch/metal
[ 413, 77, 413, 12, 1527096488 ]
def __init__(self, module): super().__init__() self.module = module
HazyResearch/metal
[ 413, 77, 413, 12, 1527096488 ]
def __init__(self, start=None, resume=False, single=False, *args, **kwargs): if resume and not start: raise ValueError('Cannot resume without a start test given.') # Initialise. unittest.TestSuite.__init__(self, *args, **kwargs) # Add the required set of non-optional, initialising tests depending on # whether the testing is to be resumed after a prior failed test run or # not. NB: this set of tests precedes the test given with 'start' (or # test 0 if 'start' not given). for case in (self.test_start, self.test_restart)[resume]: self.addTest(unittest.TestLoader().loadTestsFromTestCase(case)) # Load the first (after the required start/restart set) test (and the # remaining tests in case of single not true. This is either test 0 or # the test given with 'start'. if start: # Find indices for the given (in the 'TestCase.test_method format') # start method. The first index we need points to the given test # case (stored in self.test_list). The second one is the index of # the given test method (on a sorted list of all test methods # defined in the test case class). start_indices = self._get_case_and_method_indices(start) else: start_indices = 0, 0 # Load the given start, or the test with index 0, 0. method_list = list( unittest.TestLoader().loadTestsFromTestCase( self.test_list[start_indices[0]]) ) # We want all the subsequent methods from the selected test # case unless single is True, in which case we do not want to load any # more methods. last_method_index = start_indices[1] + 1 if single else None self.addTests( list(method_list)[start_indices[1]:last_method_index] ) # When appropriate, load tests from all the remaining (sans stop) test # cases. # We do not want to load any other (than the stop) tests in case of # single. if single: end_case_index = start_indices[0] else: end_case_index = len(self.test_list) for i in range(start_indices[0] + 1, end_case_index): self.addTest(unittest.TestLoader().loadTestsFromTestCase( self.test_list[i])) # Add the required end test(s). for case in self.test_stop: self.addTest(unittest.TestLoader().loadTestsFromTestCase(case))
quattor/aquilon
[ 12, 16, 12, 38, 1361797498 ]
def __init__(self, graph_builder, method): """Initializes the clusterer Attributes ---------- graph_builder: a GraphBuilderBase inherited transformer Class used to provide an underlying graph for NetworkX """ super(NetworkXLabelGraphClusterer, self).__init__(graph_builder) self.method = method
scikit-multilearn/scikit-multilearn
[ 817, 160, 817, 102, 1398863144 ]
def genResults(cases): results = [] for case in cases: results.append(getCount(case)) return results
tejasnikumbh/Algorithms
[ 6, 5, 6, 1, 1417624809 ]
def getCount(strCase): strChars = list(strCase) markList = [0]*len(strChars) prev = strChars[0] for i in range(1,len(strChars)): if(strChars[i] == prev): markList[i] = 1 else: prev = strChars[i] return sum(markList)
tejasnikumbh/Algorithms
[ 6, 5, 6, 1, 1417624809 ]
def audit_trigger_creator(self, session, user_class): session.execute( '''SELECT audit_table('{0}', '{{"age"}}')'''.format( user_class.__tablename__ ) )
kvesteri/postgresql-audit
[ 102, 27, 102, 19, 1423404623 ]
def user(self, session, user_class, audit_trigger_creator): user = user_class(name='John', age=15) session.add(user) session.flush() return user
kvesteri/postgresql-audit
[ 102, 27, 102, 19, 1423404623 ]
def test_update(self, user, session): user.name = 'Luke' user.age = 18 session.flush() activity = last_activity(session) assert activity['changed_data'] == {'name': 'Luke'} assert activity['old_data'] == { 'id': user.id, 'name': 'John', } assert activity['table_name'] == 'user' assert activity['native_transaction_id'] > 0 assert activity['verb'] == 'update'
kvesteri/postgresql-audit
[ 102, 27, 102, 19, 1423404623 ]
def restore(): pos, angl = q.pop() turtle.up() turtle.setposition(pos) turtle.seth(angl) turtle.down()
kvoss/lsystem
[ 8, 2, 8, 1, 1407557907 ]
def __init__(self, rho=RHO_SIL): self.cmtype = 'Silicate' self.rho = rho self.citation = "Using optical constants for astrosilicate,\nDraine, B. T. 2003, ApJ, 598, 1026\nhttp://adsabs.harvard.edu/abs/2003ApJ...598.1026D" D03file = _find_cmfile('callindex.out_sil.D03') D03dat = ascii.read(D03file, header_start=4, data_start=5) wavel = D03dat['wave(um)'] * u.micron rp = interp1d(wavel.to(u.cm).value, 1.0 + D03dat['Re(n)-1']) # wavelength (cm), rp ip = interp1d(wavel.to(u.cm).value, D03dat['Im(n)']) # wavelength (cm), ip self.interps = (rp, ip)
eblur/newdust
[ 5, 4, 5, 13, 1491452814 ]
def rp(self, lam, unit='kev'): lam_cm = c._lam_cm(lam, unit) return self._interp_helper(lam_cm, self.interps[0], rp=True)
eblur/newdust
[ 5, 4, 5, 13, 1491452814 ]
def cm(self, lam, unit='kev'): return self.rp(lam, unit=unit) + 1j * self.ip(lam, unit=unit)
eblur/newdust
[ 5, 4, 5, 13, 1491452814 ]
def fit_storage(self, table): if not isinstance(table, Storage): raise TypeError("Data is not a subclass of Orange.data.Storage.") if not all(isinstance(var, DiscreteVariable) for var in table.domain.variables): raise NotImplementedError("Only discrete variables are supported.") cont = contingency.get_contingencies(table) class_freq = np.diag( contingency.get_contingency(table, table.domain.class_var)) return NaiveBayesModel(cont, class_freq, table.domain)
qusp/orange3
[ 1, 1, 1, 2, 1430084518 ]
def __init__(self, cont, class_freq, domain): super().__init__(domain) self.cont = cont self.class_freq = class_freq
qusp/orange3
[ 1, 1, 1, 2, 1430084518 ]
def _build_request(path=None): request = Mock() request.path = path request._messages = [] # Stop messaging code trying to iterate a Mock return request
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_show_challenge(): """Test the view to show an individual challenge.""" request = _build_request('/my-project/my-challenge/') response = views.show(request, 'my-project', 'my-challenge') assert_equal(response.status_code, 200)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def assertSuccessMessage(self, response): """Assert that there is a success message in the given response.""" eq_(len(response.context['messages']), 1) eq_(list(response.context['messages'])[0].level, SUCCESS)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def setUp(self): challenge_setup()
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def tearDown(self): challenge_teardown()
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_no_entries(self): """Test that challenges display ok without any entries.""" response = self.client.get(Challenge.objects.get().get_absolute_url()) assert_equal(response.status_code, 200) # Make sure the entries are present and in reverse creation order assert_equal(len(response.context['entries'].object_list), 0)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_challenge_entries(self): """Test that challenge entries come through to the challenge view.""" submission_titles = create_submissions(3) response = self.client.get(Challenge.objects.get().get_entries_url()) assert_equal(response.status_code, 200) # Make sure the entries are present and in reverse creation order assert_equal([s.title for s in response.context['entries'].object_list], list(reversed(submission_titles)))
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_entries_view(self): """Test the dedicated entries view.
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_hidden_entries(self): """Test that draft entries are not visible on the entries page.""" create_submissions(3) submissions = Submission.objects.all() hidden_submission = submissions[0] hidden_submission.is_draft = True hidden_submission.save() phase = Phase.objects.get() response = self.client.get(phase.get_absolute_url()) # Check the draft submission is hidden assert_equal(set(response.context['entries'].object_list), set(submissions[1:]))
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_winning_entries(self): """Test the winning entries view.""" create_submissions(5) winners = Submission.objects.all()[1:3] for entry in winners: entry.is_winner = True entry.save() response = self.client.get(reverse('entries_winning')) eq_(set(e.title for e in response.context['ideation_winners']), set(e.title for e in winners)) assert_equal(len(response.context['development_winners']), 0)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def _form_from_link(link_object): return dict((k, getattr(link_object, k)) for k in ['id', 'name', 'url'])
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def setUp(self): challenge_setup() self.category_id = Category.objects.get().id self.project_slug, self.challenge_slug = (Project.objects.get().slug, Challenge.objects.get().slug) self.entry_form_path = '/en-US/%s/challenges/%s/entries/add/' % \ (self.project_slug, self.challenge_slug) create_users()
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def tearDown(self): challenge_teardown()
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_anonymous_form(self): """Check we can't display the entry form without logging in.""" response = self.client.get(self.entry_form_path) # Check it's some form of redirect assert response.status_code in xrange(300, 400)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_anonymous_post(self): """Check we can't post an entry without logging in.""" form_data = {'title': 'Submission', 'brief_description': 'A submission', 'description': 'A submission of shining wonderment.', 'created_by': User.objects.get(username='alex').id, 'category': self.category_id} response = self.client.post(self.entry_form_path, data=form_data) assert response.status_code in xrange(300, 400) assert_equal(Submission.objects.count(), 0)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_display_form(self): """Test the new entry form.""" self.client.login(username='alex', password='alex') response = self.client.get(self.entry_form_path) assert_equal(response.status_code, 200) # Check nothing gets created assert_equal(Submission.objects.count(), 0)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_submit_form(self): self.client.login(username='alex', password='alex') alex = User.objects.get(username='alex') form_data = {'title': 'Submission', 'brief_description': 'A submission', 'description': 'A submission of shining wonderment.', 'created_by': alex.get_profile(), 'category': self.category_id}
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_invalid_form(self): """Test that an empty form submission fails with errors.""" self.client.login(username='alex', password='alex') response = self.client.post(self.entry_form_path, data=BLANK_EXTERNALS) # Not so fussed about authors: we'll be re-working that soon enough
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_bad_image(self): """Test that a bad image is discarded.""" self.client.login(username='alex', password='alex') alex = User.objects.get(username='alex')
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_challenge_not_found(): """Test behaviour when a challenge doesn't exist.""" request = _build_request('/my-project/not-a-challenge/') try: response = views.show(request, 'my-project', 'not-a-challenge') except Http404: pass else: assert_equal(response.status_code, 404)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_wrong_project(): """Test behaviour when the project and challenge don't match.""" project_fields = {'name': 'Another project', 'slug': 'another-project', 'description': "Not the project you're looking for", 'long_description': 'Nothing to see here'} other_project = Project.objects.create(**project_fields) request = _build_request('/another-project/my-challenge/') # We either want 404 by exception or by response code here: either is fine try: response = views.show(request, 'another-project', 'my-challenge') except Http404: pass else: assert_equal(response.status_code, 404)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def setUp(self): self.initial_data = setup_ideation_phase(**setup_ignite_challenge()) self.profile = create_user('bob') self.submission = create_submission(created_by=self.profile, phase=self.initial_data['ideation_phase']) self.parent = self.submission.parent self.submission_path = self.submission.get_absolute_url()
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def create_submission(self, **kwargs): """Helper to create a ``Submission``""" defaults = { 'phase': self.initial_data['ideation_phase'], 'title': 'A submission', 'brief_description': 'My submission', 'description': 'My wonderful submission', 'created_by': self.profile, 'category': self.initial_data['category'], } if kwargs: defaults.update(kwargs) return Submission.objects.create(**defaults)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_show_entry(self): url = reverse('entry_show', kwargs={'entry_id': self.submission.id, 'phase': 'ideas',}) response = self.client.get(url) assert_equal(response.status_code, 200)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_entry_not_found(self): # Get an ID that doesn't exist bad_id = Submission.objects.aggregate(max_id=Max('id'))['max_id'] + 1 bad_path = '/my-project/challenges/my-challenge/entries/%d/' % bad_id response = self.client.get(bad_path) assert_equal(response.status_code, 404, response.content)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_old_versioned_entry(self): new_submission = self.create_submission(title='Updated Submission!') self.parent.update_version(new_submission) response = self.client.get(self.submission_path) assert_equal(response.status_code, 200) eq_(response.context['entry'].title, 'Updated Submission!')
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_new_versioned_entry(self): new_submission = self.create_submission(title='Updated Submission!') self.parent.update_version(new_submission) response = self.client.get(new_submission.get_absolute_url()) assert_equal(response.status_code, 200) eq_(response.context['entry'].title, 'Updated Submission!')
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_failed_versioned_entry(self): """New versioned entries shouldn't change the url""" new_submission = self.create_submission(title='Updated Submission!') self.parent.update_version(new_submission) url = reverse('entry_show', kwargs={'entry_id': new_submission.id, 'phase': 'ideas'}) response = self.client.get(url) assert_equal(response.status_code, 404)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def setUp(self): challenge_setup() phase = Phase.objects.get() phase.name = 'Ideation' phase.save() create_users() admin = User.objects.create_user('admin', 'admin@example.com', password='admin') admin.is_superuser = True admin.save() # Fill in the profile name to stop nag redirects admin_profile = admin.get_profile() admin_profile.name = 'Admin Adminson' admin_profile.save() alex_profile = User.objects.get(username='alex').get_profile() create_submissions(1, creator=alex_profile) entry = Submission.objects.get() self.view_path = entry.get_absolute_url() self.edit_path = entry.get_edit_url()
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def open_phase(self): phase = Phase.objects.get() phase.start_date = datetime.utcnow() - timedelta(hours=1) phase.end_date = datetime.utcnow() + timedelta(hours=1) phase.save()
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def _edit_data(self, submission=None): if submission is None: submission = Submission.objects.get() return dict(title=submission.title, brief_description='A submission', description='A really, seriously good submission', life_improvements='This will benefit mankind', category=submission.category.id)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_edit_form(self): self.client.login(username='alex', password='alex') response = self.client.get(self.edit_path) assert_equal(response.status_code, 200)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_edit(self): self.client.login(username='alex', password='alex') data = self._edit_data() data.update(BLANK_EXTERNALS) response = self.client.post(self.edit_path, data, follow=True) self.assertRedirects(response, self.view_path) # Check for a success message self.assertSuccessMessage(response) assert_equal(Submission.objects.get().description, data['description'])
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_edit_closed_phase(self): self.close_phase() self.client.login(username='alex', password='alex') data = self._edit_data() data.update(BLANK_EXTERNALS) response = self.client.post(self.edit_path, data, follow=True) eq_(response.status_code, 403)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_anonymous_access(self): """Check that anonymous users can't get at the form.""" response = self.client.get(self.edit_path) assert_equal(response.status_code, 302)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_anonymous_edit(self): """Check that anonymous users can't post to the form.""" data = self._edit_data() data.update(BLANK_EXTERNALS) response = self.client.post(self.edit_path, data) assert_equal(response.status_code, 302) assert 'seriously' not in Submission.objects.get().description
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_non_owner_access(self): """Check that non-owners cannot see the edit form.""" self.client.login(username='bob', password='bob') response = self.client.get(self.edit_path) assert_equal(response.status_code, 403)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_non_owner_edit(self): """Check that users cannot edit each other's submissions.""" self.client.login(username='bob', password='bob') data = self._edit_data() data.update(BLANK_EXTERNALS) response = self.client.post(self.edit_path, data) assert_equal(response.status_code, 403) assert 'seriously' not in Submission.objects.get().description
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_admin_access(self): """Check that administrators can see the edit form.""" self.client.login(username='admin', password='admin') response = self.client.get(self.edit_path) assert_equal(response.status_code, 200)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_admin_edit(self): """Check that administrators can edit submissions.""" self.client.login(username='admin', password='admin') data = self._edit_data() data.update(BLANK_EXTERNALS) response = self.client.post(self.edit_path, data) self.assertRedirects(response, self.view_path) assert_equal(Submission.objects.get().description, data['description']) self.client.logout()
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def setUp(self): self.initial_data = setup_ideation_phase(**setup_ignite_challenge()) self.profile = create_user('bob') self.submission = create_submission(created_by=self.profile, phase=self.initial_data['ideation_phase']) self.view_path = self.submission.get_absolute_url() self.edit_path = self.submission.get_edit_url() ExternalLink.objects.create(submission=self.submission, name='Foo', url='http://example.com/') ExternalLink.objects.create(submission=self.submission, name='Foo', url='http://example.net/') self.client.login(username='bob', password='bob')
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def _base_form(self): submission = Submission.objects.get() return {'title': submission.title, 'brief_description': submission.brief_description, 'description': submission.description, 'life_improvements': 'This will benefit mankind', 'category': submission.category.id}
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_preserve_links(self): """Test submission when the links are not changed.""" form_data = self._base_form() links = ExternalLink.objects.all() form_data.update(_build_links(2, *map(_form_from_link, links))) response = self.client.post(self.edit_path, form_data) self.assertRedirects(response, self.view_path) eq_(ExternalLink.objects.count(), 2)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_remove_links(self): """Test submission with blank link boxes. All the links should be deleted, as the forms are blank.""" form_data = self._base_form() links = ExternalLink.objects.all() link_forms = [{'id': link.id} for link in links] form_data.update(_build_links(2, *link_forms)) response = self.client.post(self.edit_path, form_data) self.assertRedirects(response, self.view_path) eq_(ExternalLink.objects.count(), 0)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_add_links(self): """Test adding links to a submission without any.""" ExternalLink.objects.all().delete() form_data = self._base_form() link_forms = [{'name': 'Cheese', 'url': 'http://cheese.com/'}, {'name': 'Pie', 'url': 'http://en.wikipedia.org/wiki/Pie'}] form_data.update(_build_links(0, *link_forms)) response = self.client.post(self.edit_path, form_data) self.assertRedirects(response, self.view_path) eq_(ExternalLink.objects.count(), 2) cheese_link = ExternalLink.objects.get(name='Cheese') eq_(cheese_link.url, 'http://cheese.com/') eq_(cheese_link.submission, Submission.objects.get())
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def setUp(self): challenge_setup() create_users() phase = Phase.objects.get() phase.name = 'Ideation' phase.save() self.alex_profile = User.objects.get(username='alex').get_profile() submission = self.create_submission() self.parent = SubmissionParent.objects.create(submission=submission) base_kwargs = {'project': Project.objects.get().slug, 'slug': Challenge.objects.get().slug} self.view_path = submission.get_absolute_url() self.delete_path = submission.get_delete_url()
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_anonymous_delete_form(self): """Check that anonymous users can't get at the form.""" response = self.client.get(self.delete_path) assert_equal(response.status_code, 302)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_anonymous_delete(self): """Check that anonymous users can't delete entries.""" response = self.client.post(self.delete_path) assert_equal(response.status_code, 302)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_non_owner_access(self): """Check that non-owners cannot see the delete form.""" self.client.login(username='bob', password='bob') response = self.client.get(self.delete_path) assert_equal(response.status_code, 404)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_non_owner_delete(self): """Check that users cannot delete each other's submissions.""" self.client.login(username='bob', password='bob') response = self.client.post(self.delete_path, {}) assert_equal(response.status_code, 404) assert Submission.objects.exists()
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_delete_form(self): self.client.login(username='alex', password='alex') response = self.client.get(self.delete_path) assert_equal(response.status_code, 200)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]
def test_delete(self): self.client.login(username='alex', password='alex') response = self.client.post(self.delete_path, {}, follow=True) assert_equal(response.redirect_chain[0][1], 302) assert_equal((Submission.objects.filter(created_by=self.alex_profile) .count()), 0) self.assertSuccessMessage(response) assert_equal((SubmissionParent.objects .filter(submission__created_by=self.alex_profile) .count()), 0)
mozilla/mozilla-ignite
[ 13, 15, 13, 6, 1319036985 ]