Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update form for adding distribution #639

Merged
merged 2 commits into from
Oct 26, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 0 additions & 43 deletions anitya/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import logging

import flask
from sqlalchemy.exc import SQLAlchemyError

from anitya.lib import utilities
from anitya.db import models, Session
Expand All @@ -27,48 +26,6 @@ def is_admin(user=None):
return user.admin


@ui_blueprint.route('/distro/add', methods=['GET', 'POST'])
@login_required
def add_distro():

if not is_admin():
flask.abort(401)

form = anitya.forms.DistroForm()

if form.validate_on_submit():
name = form.name.data

distro = models.Distro(name)

utilities.log(
Session,
distro=distro,
topic='distro.add',
message=dict(
agent=flask.g.user.username,
distro=distro.name,
)
)

try:
Session.add(distro)
Session.commit()
flask.flash('Distribution added')
except SQLAlchemyError:
Session.rollback()
flask.flash(
'Could not add this distro, already exists?', 'error')
return flask.redirect(
flask.url_for('anitya_ui.distros')
)

return flask.render_template(
'distro_add.html',
current='distros',
form=form)


@ui_blueprint.route('/distro/<distro_name>/edit', methods=['GET', 'POST'])
@login_required
def edit_distro(distro_name):
Expand Down
11 changes: 10 additions & 1 deletion anitya/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,10 @@ class FlagProjectForm(FlaskForm):


class MappingForm(FlaskForm):
distro = StringField('Distribution', [validators.DataRequired()])
distro = SelectField(
'Distribution',
[validators.DataRequired()],
choices=[])
package_name = StringField('Package name', [validators.DataRequired()])

def __init__(self, *args, **kwargs):
Expand All @@ -81,6 +84,12 @@ def __init__(self, *args, **kwargs):
self.version_url.data = package.version_url
self.regex.data = package.regex

if 'distros' in kwargs:
self.distro.choices = [
(distro, distro)
for distro in sorted(kwargs['distros'], key=lambda s: s.lower())
]


class ConfirmationForm(FlaskForm):
pass
Expand Down
63 changes: 60 additions & 3 deletions anitya/templates/distro_add.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<h1>Add a new disribution</h1>
</div>

<form method="POST" action="{{ url_for('anitya_ui.add_distro') }}" >
<form id="distro" method="POST" action="{{ url_for('anitya_ui.add_distro') }}" >
<div class="row">
<div class="col-md-6">
<div class="list-group">
Expand All @@ -36,11 +36,68 @@ <h1>Add a new disribution</h1>
</a>
{{ form.csrf_token }}
</form>

<br/>
<div class="row">
<div class="col-md-6" id="info_field">
<div class="list-group">
<span class="list-group-item">
<p id="info_field_title"></p>
<ul id="info_field_list"></ul>
</span>
</div>
</div>
</div>
{% endblock %}

{% block jscript %}
<script type="text/javascript">
$("#name").prop('title', "Official distribution name");
function check_name() {
var _name = $('#name').val().trim();
if (_name) {
show_similar_distros();
} else {
$('#info_field_list').html('');
$('#info_field').hide();
}
}

function show_similar_distros() {
$.getJSON(
"{{ url_for('anitya_apiv1.api_distro_names') }}", {
pattern: $("#name").val().trim()
})
.done(function( res ) {
$('#info_field_list').html('');
if (res.total > 0){
$('#info_field_title').html('Distros with the similar name');
for (i = 0; i < res.distro.length; i++){
$('#info_field_list').append(
'<li>'+ res.distro[i] + '</li>');
}
$('#info_field').show();
} else {
$('#info_field').hide();
}
});
}

$(document).ready(function(){
check_name();
$("#name").prop('title', "Official distribution name");
$("#name").focusout(function() {
check_name()
});
$("#distro").submit(function( event ) {
if ($('#info_field_list').html()) {
var items = [];
$("#info_field li").each(function(index) {
items.push($(this).text());
});
response = confirm("Are you sure you want to create this distro?\n\n" +
"There are distro(s) with similar name(s):\n" + items.join("\r\n"));
return response;
}
});
});
</script>
{% endblock %}
14 changes: 6 additions & 8 deletions anitya/templates/distros.html
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,14 @@ <h1>Distributions participating</h1>
<p>
Here is the list of all the distributions that anitya knows about.
</p>
{% if is_admin %}
<p>
<a href="{{ url_for('anitya_ui.add_distro') }}">
<button type="submit" class="btn btn-success">
<span class="glyphicon glyphicon-edit"></span>
Add a new distribution
</button>
</a>
<a href="{{ url_for('anitya_ui.add_distro') }}">
<button type="submit" class="btn btn-success">
<span class="glyphicon glyphicon-edit"></span>
Add a new distribution
</button>
</a>
</p>
{% endif %}
<div class="list-group">
{% for distro in distros %}
<span class="list-group-item">
Expand Down
88 changes: 48 additions & 40 deletions anitya/templates/mapping.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,50 +9,58 @@
<h1>Project: {{ project.name }}</h1>
</div>

<div class="row">

{% if package %}
<form method="POST" action="{{ url_for('anitya_ui.edit_project_mapping',
project_id=project.id, pkg_id=package.id) }}" >
{% else %}
<form method="POST" action="{{ url_for('anitya_ui.map_project', project_id=project.id) }}" >
{% endif %}
{{ form.csrf_token }}
<div class="row">
<div class="col-md-6">
<div class="list-group">
<span class="list-group-item">
<table class="table table-condensed">
<tr>
{{ render_field_in_row(form.distro) }}
<td></td>
</tr>

<tr>
{{ render_field_in_row(form.package_name) }}
<td></td>
</tr>
</table>
</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-success">
{% if package %}
<form method="POST" action="{{ url_for('anitya_ui.edit_project_mapping',
project_id=project.id, pkg_id=package.id) }}" >
<span class="glyphicon glyphicon-refresh"></span>
Edit mapping
{% else %}
<form method="POST" action="{{ url_for('anitya_ui.map_project', project_id=project.id) }}" >
<span class="glyphicon glyphicon-plus"></span>
Add mapping to project
{% endif %}
{{ form.csrf_token }}
<table id="input_table">

<tr>
{{ render_field_in_row(form.distro) }}
<td></td>
</tr>

<tr>
{{ render_field_in_row(form.package_name) }}
<td></td>
</tr>

</table>

<div class="clearfix"></div>

<button type="submit" class="btn btn-success">
{% if package %}
<span class="glyphicon glyphicon-refresh"></span>
Edit mapping
{% else %}
<span class="glyphicon glyphicon-plus"></span>
Add mapping project
{% endif %}
</button>

<a href="{{ url_for('anitya_ui.project', project_id=project.id) }}">
<button type="button" class="btn btn-danger">
<span class="glyphicon glyphicon-ban-circle"></span>
Cancel
</button>
</a>

</form>

</button>

<a href="{{ url_for('anitya_ui.project', project_id=project.id) }}">
<button type="button" class="btn btn-danger">
<span class="glyphicon glyphicon-ban-circle"></span>
Cancel
</button>
</a>
</form>
<br/>
<div class="row">
<div class="col-md-6">
<p>
Missing your favorite distribution?<br\>
You can add it through <a href="{{ url_for('anitya_ui.distros') }}">distros</a>
</p>
</div>
</div>

{% endblock %}
Expand Down
73 changes: 70 additions & 3 deletions anitya/tests/test_flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@ def test_map_project(self):
b'name="csrf_token" type="hidden" value="')[1].split(b'">')[0]
data = {
'package_name': 'geany',
'distro': 'CentOS',
'distro': 'Fedora',
'csrf_token': csrf_token,
}

Expand All @@ -782,7 +782,7 @@ def test_map_same_distro(self):
b'name="csrf_token" type="hidden" value="')[1].split(b'">')[0]
data = {
'package_name': 'geany',
'distro': 'CentOS',
'distro': 'Fedora',
'csrf_token': csrf_token,
}

Expand All @@ -793,7 +793,7 @@ def test_map_same_distro(self):
self.assertTrue(
b'<li class="list-group-item list-group-item-danger">'
b'Could not edit the mapping of geany on '
b'CentOS, there is already a package geany on CentOS '
b'Fedora, there is already a package geany on Fedora '
b'as part of the project <a href="/project/1/">geany'
b'</a>.</li>'
in output.data)
Expand Down Expand Up @@ -919,3 +919,70 @@ def test_invalid_project_id(self):
with login_user(self.flask_app, self.user):
output = self.client.post('/project/42/map/1', data={})
self.assertEqual(output.status_code, 404)


class AddDistroTests(DatabaseTestCase):
"""Tests for the :func:`anitya.admin.add_distro` view function."""

def setUp(self):
super(AddDistroTests, self).setUp()

# Add a regular user and an admin user
session = Session()
self.user = models.User(
email='[email protected]',
username='user',
)
user_social_auth = social_models.UserSocialAuth(
user_id=self.user.id,
user=self.user
)

session.add(self.user)
session.add(user_social_auth)
session.commit()

self.client = self.flask_app.test_client()

def test_no_csrf_token(self):
"""Assert submitting without a CSRF token, no change is made."""
with login_user(self.flask_app, self.user):
output = self.client.post('/distro/add', data={'name': 'Fedora'})
self.assertEqual(200, output.status_code)
self.assertEqual(0, models.Distro.query.count())

def test_invalid_csrf_token(self):
"""Assert submitting with an invalid CSRF token, no change is made."""
with login_user(self.flask_app, self.user):
output = self.client.post('/distro/add', data={'csrf_token': 'abc', 'name': 'Fedora'})
self.assertEqual(200, output.status_code)
self.assertEqual(0, models.Distro.query.count())

def test_add_distro(self):
"""Assert admins can add distributions."""
with login_user(self.flask_app, self.user):
output = self.client.get('/distro/add')
csrf_token = output.data.split(
b'name="csrf_token" type="hidden" value="')[1].split(b'">')[0]
data = {'name': 'Fedora', 'csrf_token': csrf_token}

output = self.client.post('/distro/add', data=data, follow_redirects=True)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does self.client.post() assert that the return code is 200 by default?


self.assertEqual(200, output.status_code)
self.assertTrue(b'Distribution added' in output.data)

def test_duplicate_distro(self):
"""Assert trying to create a duplicate distribution results in HTTP 409."""
with login_user(self.flask_app, self.user):
output = self.client.get('/distro/add')
csrf_token = output.data.split(
b'name="csrf_token" type="hidden" value="')[1].split(b'">')[0]
data = {'name': 'Fedora', 'csrf_token': csrf_token}

create_output = self.client.post('/distro/add', data=data, follow_redirects=True)
self.assertEqual(200, output.status_code)
dup_output = self.client.post('/distro/add', data=data, follow_redirects=True)

self.assertEqual(200, output.status_code)
self.assertTrue(b'Distribution added' in create_output.data)
self.assertTrue(b'Could not add this distro' in dup_output.data)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like it'd be good to assert that an HTTP error code was used here. Perhaps 409 (conflict)?

Suggested change
self.assertTrue(b'Could not add this distro' in dup_output.data)
self.assertTrue(b'Could not add this distro' in dup_output.data)
self.assertEqual(409, output.status_code)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user is redirected to /distros page, so the user gets 301 redirect.

Loading