Repository: MechanicalSoup/MechanicalSoup

Issue:
Manage <select multiple>
`<select multiple>` should behave essentially like multiple checkboxes with the same name. For now, they don't: selecting one option deselects the previous ones.

@hemberger: while you're working on form, you may want to fix this too.

Discussion:
hemberger: Yep! This will always work since `Form.set` is now a direct wrapper around `Form.set_*`. (The only difference is that `set` can only take one name-value pair, but value can be as many elements as the `set_*` method allows.

I can certainly change the test from
```
form.set_select({'instrument': options)
```
to
```
browser['instrument'] = options
```
I only chose the former because it made it more explicit that it was testing `set_select`. Which would you prefer?

Patch:
diff --git a/docs/ChangeLog.rst b/docs/ChangeLog.rst
index 63d2685..7ba5011 100644
--- a/docs/ChangeLog.rst
+++ b/docs/ChangeLog.rst
@@ -40,6 +40,9 @@ Main changes:
   ``browser.get_current_form().print_summary()`` to get a summary of the
   fields you need to fill-in (and which ones are already filled-in).
 
+* The ``Form`` class now supports selecting multiple options in
+  a ``<select multiple>`` element.
+
 Bug fixes
 ---------
 
diff --git a/mechanicalsoup/form.py b/mechanicalsoup/form.py
index 258b1e2..8fb7440 100644
--- a/mechanicalsoup/form.py
+++ b/mechanicalsoup/form.py
@@ -185,17 +185,30 @@ class Form(object):
         :param data: Dict of ``{name: value, ...}``.
             Find the select element whose *name*-attribute is ``name``.
             Then select from among its children the option element whose
-            *value*-attribute is ``value``.
+            *value*-attribute is ``value``. If the select element's
+            *multiple*-attribute is set, then ``value`` can be a list
+            or tuple to select multiple options.
         """
         for (name, value) in data.items():
             select = self.form.find("select", {"name": name})
             if not select:
                 raise InvalidFormMethod("No select named " + name)
+
+            # Deselect all options first
             for option in select.find_all("option"):
                 if "selected" in option.attrs:
                     del option.attrs["selected"]
-            o = select.find("option", {"value": value})
-            o.attrs["selected"] = "selected"
+
+            # Wrap individual values in a 1-element tuple.
+            # If value is a list/tuple, select must be a <select multiple>.
+            if not isinstance(value, list) and not isinstance(value, tuple):
+                value = (value,)
+            elif "multiple" not in select.attrs:
+                raise LinkNotFoundError("Cannot select multiple options!")
+
+            for choice in value:
+                option = select.find("option", {"value": choice})
+                option.attrs["selected"] = "selected"
 
     def __setitem__(self, name, value):
         """Forwards arguments to :func:`~Form.set`. For example,


Test patch:
diff --git a/tests/test_form.py b/tests/test_form.py
index 29530b3..6e9e765 100644
--- a/tests/test_form.py
+++ b/tests/test_form.py
@@ -253,6 +253,41 @@ def test_set_select(option):
     assert(res.status_code == 200 and res.text == 'Success!')
     browser.close()
 
+
+set_select_multiple_form = '''
+<form method="post" action="mock://form.com/post">
+  <select name="instrument" multiple>
+    <option value="piano">Piano</option>
+    <option value="bass">Bass</option>
+    <option value="violin">Violin</option>
+  </select>
+  <input type="submit" value="Select Multiple" />
+</form>
+'''
+
+@pytest.mark.parametrize("options", [
+    pytest.param('bass', id='select one (str)'),
+    pytest.param(('bass',), id='select one (tuple)'),
+    pytest.param(('piano', 'violin'), id='select two'),
+])
+def test_set_select_multiple(options):
+    """Test a <select multiple> element."""
+    # When a browser submits multiple selections, the qsl looks like:
+    #  name=option1&name=option2
+    if not isinstance(options, list) and not isinstance(options, tuple):
+        expected = (('instrument', options),)
+    else:
+        expected = (('instrument', option) for option in options)
+    browser, url = setup_mock_browser(expected_post=expected,
+                                      text=set_select_multiple_form)
+    browser.open(url)
+    form = browser.select_form('form')
+    form.set_select({'instrument': options})
+    res = browser.submit_selected()
+    assert(res.status_code == 200 and res.text == 'Success!')
+    browser.close()
+
+
 page_with_missing_elements = '''
 <html>
   <form method="post">
@@ -294,6 +329,8 @@ def test_form_not_found():
         form.textarea({'bar': 'value', 'foo': 'nosuchval'})
     with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
         form.set_radio({'size': 'tiny'})
+    with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
+        form.set_select({'entree': ('no_multiple', 'no_multiple')})
     browser.close()
 
 page_with_radio = '''