def _roll(dicenumber, dicesetid): form = StoryForm() try: dice = DiceSet(dicesetid) except NonExistingSetError: abort(404) try: roll = dice.throw_dice(dicenumber) phrase = "" for elem in roll: phrase = phrase + elem + " " except WrongDiceNumberError: return _stories( "<div class=\"alert alert-danger alert-dismissible fade show\">" + "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>" + "<strong>Error!</strong> Wrong dice number!</div>") except WrongArgumentTypeError: return _stories( "<div class=\"alert alert-danger alert-dismissible fade show\">" + "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>" + "<strong>Error!</strong> Argument Dice number needs to be an integer!</div>" ) return render_template("create_story.html", form=form, set=dicesetid, roll=roll, phrase=phrase)
def test_multi_die_multi_face(self): random.seed(0) # 1, 1, 0, 1, 2, 1, ... die1 = Die(["1", "2", "3"], "test_theme") die2 = Die(["4", "5", "6"], "test_theme") dice_set = DiceSet([die1, die2], "test_theme") self.assertEqual(_throw_to_faces(dice_set.throw()), ["2", "5"]) self.assertEqual(_throw_to_faces(dice_set.throw()), ["1", "5"]) self.assertEqual(_throw_to_faces(dice_set.throw()), ["3", "5"])
def test_single_die_multi_face(self): random.seed(0) # 1, 1, 0, 1, 2, ... die = Die(["1", "2", "3"], "test_theme") dice_set = DiceSet([die], "test_theme") self.assertEqual(_throw_to_faces(dice_set.throw()), ["2"]) self.assertEqual(_throw_to_faces(dice_set.throw()), ["2"]) self.assertEqual(_throw_to_faces(dice_set.throw()), ["1"]) self.assertEqual(_throw_to_faces(dice_set.throw()), ["2"]) self.assertEqual(_throw_to_faces(dice_set.throw()), ["3"])
def test_empty_story(): diceset = 'standard' dicenum = 6 dice = DiceSet(diceset, dicenum) roll = dice.throw_dice() story = '' with pytest.raises(NotValidStoryError): _check_story(roll, story)
def test_correct_story(): diceset = 'standard' dicenum = 6 dice = DiceSet(diceset, dicenum) roll = dice.throw_dice() story = '' for word in roll: story += word + ' ' _check_story(roll, story)
def test_dice_init(self): # correct init dice = DiceSet('basic') self.assertEqual(len(dice.dice), 6) check1 = ['tulip', 'mouth', 'caravan', 'clock', 'whale', 'drink'] self.assertEqual(dice.dice[1].faces, check1) # non existing dice set with self.assertRaises(NonExistingSetError): DiceSet('pippo')
def test_throw_and_serialize_dice_set(self): rnd.seed(574891) die1 = Die(path + "die0.txt") die2 = Die(path + "die1.txt") die3 = Die(path + "die2.txt") dice = [die1, die2, die3] dice_set = DiceSet(dice) # throw dice expected_res = ['bag', 'clock', 'bus'] self.assertEqual(dice_set.throw_dice(), expected_res) # serialize set serialized_set = dice_set.serialize() expected_serialized_set = json.dumps(dice_set.pips) self.assertEqual(serialized_set, expected_serialized_set)
def test_dice_pipes(self): dice = DiceSet('basic') die0 = ['bike', 'moonandstars', 'bag', 'bird', 'crying', 'angry'] die1 = ['tulip', 'mouth', 'caravan', 'clock', 'whale', 'drink'] die2 = ['happy', 'coffee', 'plate', 'bus', 'letter', 'paws'] die3 = ['cat', 'pencil', 'baloon', 'bananas', 'phone', 'icecream'] #die4 = ['ladder', 'car', 'fire', 'bang', 'hat', 'hamburger'] #die5 = ['rain', 'heart', 'glasses', 'poo', 'ball', 'sun'] result = dice.throw_dice("4") #print(result) self.assertEqual(len(result), 4) self.assertIn(result[0], die0) self.assertIn(result[1], die1) self.assertIn(result[2], die2) self.assertIn(result[3], die3) #self.assertIn(result[4], die4) #self.assertIn(result[5], die5) # wrong argument type with self.assertRaises(WrongArgumentTypeError): dice.throw_dice("pippo") # wrong dice number with self.assertRaises(WrongDiceNumberError): dice.throw_dice("10")
def _rollDice(): ''' Rolls the dice and enables the user to start writing a story. The story is created as a draft, so that it can be edited. Raises: Exception: due to eventual failures during the commit of the created story into the database. Returns: 302 -> the user is redirected to the page in which he/she can start writing the story on the faces which came out. ''' diceset = request.args.get('diceset', 'standard') dicenum = request.args.get('dicenum', 6, type=int) try: dice = DiceSet(diceset, dicenum) roll = dice.throw_dice() story = Story() story.text = '' story.theme = diceset story.likes = 0 story.dislikes = 0 story.dice_set = roll story.author_id = current_user.id db.session.add(story) db.session.commit() except Exception as e: print(e) db.session.rollback() abort(400) return redirect(url_for('stories._story_edit', storyid=story.id))
def test_single_die_single_face(self): die = Die(["1"], "test_theme") dice_set = DiceSet([die], "test_theme") self.assertEqual(_throw_to_faces(dice_set.throw()), ["1"])
def test_multi_die_single_face(self): die1 = Die(["1"], "test_theme") die2 = Die(["2"], "test_theme") dice_set = DiceSet([die1, die2], "test_theme") self.assertEqual(_throw_to_faces(dice_set.throw()), ["1", "2"])
def _roll_dice(): # check dice_number try: # get number of dice from the form of previous page dice_number = int(request.form['dice_number']) session['dice_number'] = dice_number # check retrieved data if dice_number not in range(2, 7): raise ValueError except BadRequestKeyError: # i'm here after re-rolling dice dice_number = session['dice_number'] except (KeyError, ValueError): # i'm here directly, have to go from settings before flash('Invalid number of dice!', 'error') session.pop('dice_number', None) return redirect(url_for('dice._settings')) # check dice_set try: # get dice set from the form of previous page dice_img_set = str(request.form['dice_img_set']) session['dice_img_set'] = dice_img_set # check retrieved data if dice_img_set not in {'standard', 'animal', 'halloween', 'emptyset'}: raise ValueError except BadRequestKeyError: # i'm here after re-rolling dice dice_img_set = session['dice_img_set'] except (KeyError, ValueError): # i'm here directly, have to go from settings before flash('Invalid dice set!', 'error') session.pop('dice_img_set', None) return redirect(url_for('dice._settings')) # random sampling dice and throw them dice_indexes = rnd.sample(range(0, 6), dice_number) dice_list = [] for i in dice_indexes: try: dirname = os.path.dirname(os.path.abspath(__file__)) path = dirname + "/../resources/" + dice_img_set + "/" dice_list.append(Die(path + 'die' + str(i) + '.txt')) except (FileNotFoundError, IndexError): session.pop('dice_number', None) session.pop('dice_img_set', None) flash("Can't find dice on server", 'error') return redirect(url_for('dice._settings')) dice_set = DiceSet(dice_list) dice_set.throw_dice() session['figures'] = dice_set.pips context_vars = { 'dice_number': dice_number, 'dice_img_set': dice_img_set, 'dice_indexes': dice_indexes, 'words': dice_set.pips, 'home_url': HOME_URL } return render_template('roll_dice.html', **context_vars)
def create_app(test=False): app = Flask(__name__, static_url_path='/static') app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY' app.config['SECRET_KEY'] = 'ANOTHER ONE' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///storytellers.db' if test: app.config['TESTING'] = True app.config['CELERY_ALWAYS_EAGER'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False celery = celeryApp.make_celery(app) celeryApp.celery = celery for bp in blueprints: app.register_blueprint(bp) bp.app = app db.init_app(app) login_manager.init_app(app) db.create_all(app=app) with app.app_context(): # Create first admin user. q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() example = Story() example.title = 'My first story!' example.rolls_outcome = '[["bike", "static/Mountain/bike.PNG"], ["bus", "static/Mountain/bus.PNG"]]' example.text = 'With my bike, I am faster than a bus!!!!' example.theme = 'Mountain' example.published = 1 example.likes = 42 example.dislikes = 5 example.author_id = 1 db.session.add(example) db.session.commit() # Create dice sets if missing. themes = retrieve_themes() if not themes: die1 = Die( ['angry', 'bag', 'bike', 'bird', 'crying', 'moonandstars'], "N/A") die2 = Die(['bus', 'coffee', 'happy', 'letter', 'paws', 'plate'], "N/A") die3 = Die( ['caravan', 'clock', 'drink', 'mouth', 'tulip', 'whale'], "N/A") die4 = Die( ['baloon', 'bananas', 'cat', 'icecream', 'pencil', 'phone'], "N/A") dice_set = DiceSet([die1, die2, die3], "Mountain") store_dice_set(dice_set) dice_set = DiceSet([die2, die3, die4], "Late night") store_dice_set(dice_set) dice_set = DiceSet([die3, die1, die4], "Travelers") store_dice_set(dice_set) dice_set = DiceSet([die2, die1, die4], "Youth") store_dice_set(dice_set) die = Die(["1", "2", "3"], "test_theme") dice_set = DiceSet([die], "test_theme") return app
def test_create_dice_set_with_size(self): diceset = DiceSet('standard', 6) thrown = diceset.throw_dice() self.assertEqual(len(thrown), 6)
def test_correct_dices_thrown(self): diceset = DiceSet('standard', 6) thrown = diceset.throw_dice() for i in range(6): face_list = get_die_faces_list("standard", i) self.assertTrue(thrown[i] in face_list)
def test_empty_dice_set(self): with self.assertRaises(TypeError): DiceSet()